MQ_CloudONS阿里消息队列

本文介绍如何使用C# SDK连接阿里云消息队列服务,包括环境准备、账号申请、SDK导入等步骤,并提供了创建消息生产者、发送消息的具体代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考文档

https://www.zybuluo.com/iamfox/note/239385 

环境准备

1.申请阿里云账号,开通消息队列服务,申请accessKey。

2.SDK导入(c++): ManagedONS.dll, ONSClient4CPP.exp(阿里后台下载)

3.添加引用(c#):ManagedONS.dll

 

using ons;

namespace MQTask
{
    class Program
    {
        static void Main(string[] args)
        {
            //申请账号
            string ConsumerId = GetConsumerId();
            string ProducerId = GetProducerId();
            string OrderTopic = ConfigurationSettings.AppSettings["OrderTopic"];
            string Topic = ConfigurationSettings.AppSettings["Topic"];
            string SecretKey = GetSecretKey();
            string AccessKey = GetAccessKey();

            //创建工厂
            ONSFactoryProperty factoryInfo = new ONSFactoryProperty();

            factoryInfo.setFactoryProperty(ONSFactoryProperty.AccessKey, AccessKey);
            factoryInfo.setFactoryProperty(ONSFactoryProperty.SecretKey, SecretKey);
            factoryInfo.setFactoryProperty(ONSFactoryProperty.ConsumerId, ConsumerId);
            factoryInfo.setFactoryProperty(ONSFactoryProperty.ProducerId, ProducerId);
            factoryInfo.setFactoryProperty(ONSFactoryProperty.PublishTopics, Topic);

            //创建producer
            Producer pProducer = ONSFactory.getInstance().createProducer(factoryInfo);
            //在发送消息前,必须调用start方法来启动Producer,只需调用一次即可。   
            pProducer.start();

            ////确定消费完成后,调用shutdown函数;在应用退出前,必须销毁Consumer 对象,否则会导致内存泄露等问题
            // pConsumer.shutdown();
        }

        public static SendResultONS sendmsg(Producer pProducer, string topic, string tag, string json, string keys)
        {

            string json1 = HttpUtility.UrlEncode(json);
            Message msg = new Message(
                //Message Topic
                        topic,
                //Message Tag,可理解为Gmail中的标签,对消息进行再归类,方便Consumer指定过滤条件在ONS服务器过滤        
                        tag,
                //Message Body,任何二进制形式的数据,ONS不做任何干预,需要Producer与Consumer协商好一致的序列化和反序列化方式
                        json1
            );

            // 设置代表消息的业务关键属性,请尽可能全局唯一。
            // 以方便您在无法正常收到消息情况下,可通过ONS Console查询消息并补发。
            // 注意:不设置也不会影响消息正常收发
            msg.setKey(keys);

            //发送消息,只要不抛异常就是成功    
            SendResultONS sendResult = null;
            try
            {
                sendResult = pProducer.send(msg);
            }
            catch
            {
                //异常处理
                return null;
            }

            return sendResult;
        }

        public static void getmsg(PushConsumer pConsumer)
        {
            MessageListener msgListener = new MyMsgListener();
            pConsumer.subscribe(Topic, "*", msgListener);
        }

        public class MyMsgListener : MessageListener
        {
            public MyMsgListener()
            {
            }

            ~MyMsgListener()
            {
            }

            public override ons.Action consume(Message value, ConsumeContext context)
            {
                string getTopic = value.getTopic();
                string getTag = value.getTag();
                string getKey = value.getKey();
                string getMsgID = value.getMsgID();
                string getBody = value.getBody();

                return ons.Action.CommitMessage;
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/a735882640/p/8397530.html

### 在 C++ 中使用 `mq_open` 创建和打开 POSIX 消息队列 POSIX 消息队列为进程间通信提供了可靠的方法。通过调用 `mq_open` 函数,可以在 C++ 程序中创建或打开一个消息队列。 #### 函数原型 以下是 `mq_open` 的函数声明: ```c #include <mqueue.h> int mq_open(const char *name, int oflags); int mq_open(const char *name, int oflags, mode_t mode, struct mq_attr *attr); ``` - **参数说明** - `const char *name`: 要操作的消息队列名称,通常以 `/` 开头[^1]。 - `int oflags`: 定义打开模式,类似于文件操作中的标志位(如 `O_RDONLY`, `O_WRONLY`, 或 `O_RDWR`)。如果希望创建新的消息队列,则需设置为 `O_CREAT`[^1]。 - `mode_t mode`: 当设置了 `O_CREAT` 标志时,此参数指定权限掩码,决定其他用户对该消息队列的操作权限。 - `struct mq_attr *attr`: 可选参数,当创建新队列时定义其属性;若仅是打开现有队列则可设为空指针 `NULL`。 #### 示例代码:创建并打开 POSIX 消息队列 以下是一个完整的示例,展示了如何在 C++ 中使用 `mq_open` 创建和打开一个 POSIX 消息队列: ```cpp #include <iostream> #include <string> #include <cstdlib> #include <sys/stat.h> #include <fcntl.h> #include <mqueue.h> #include <unistd.h> #include <cstring> #define QUEUE_NAME "/my_message_queue" #define MAX_MESSAGES 10 #define MESSAGE_SIZE 256 #define PERMISSIONS (S_IRUSR | S_IWUSR) int main() { // 设置消息队列的属性 struct mq_attr attr; attr.mq_flags = 0; // 非阻塞标志 attr.mq_maxmsg = MAX_MESSAGES; // 最大消息数量 attr.mq_msgsize = MESSAGE_SIZE; // 单条消息的最大长度 attr.mq_curmsgs = 0; // 当前消息数量 // 尝试创建一个新的消息队列 mqd_t mqdes = mq_open(QUEUE_NAME, O_CREAT | O_EXCL | O_RDWR, PERMISSIONS, &attr); if (mqdes == (mqd_t)-1) { perror("mq_open failed"); // 如果失败,可能是因为队列已存在 if (errno == EEXIST) { std::cerr << "Message queue already exists. Opening it..." << std::endl; // 如果队列已经存在,则尝试只打开它 mqdes = mq_open(QUEUE_NAME, O_RDWR); if (mqdes == (mqd_t)-1) { perror("mq_open failed again"); exit(EXIT_FAILURE); } } else { exit(EXIT_FAILURE); } } std::cout << "Message queue created/opened successfully." << std::endl; // 获取消息队列的状态信息 struct mq_attr currentAttr; if (mq_getattr(mqdes, &currentAttr) != 0) { perror("mq_getattr failed"); exit(EXIT_FAILURE); } std::cout << "Current attributes:" << std::endl; std::cout << "\tMaximum messages: " << currentAttr.mq_maxmsg << std::endl; std::cout << "\tMessage size: " << currentAttr.mq_msgsize << std::endl; std::cout << "\tCurrent number of messages: " << currentAttr.mq_curmsgs << std::endl; // 关闭消息队列描述符 if (mq_close(mqdes) != 0) { perror("mq_close failed"); exit(EXIT_FAILURE); } // 删除消息队列 if (mq_unlink(QUEUE_NAME) != 0) { perror("mq_unlink failed"); exit(EXIT_FAILURE); } std::cout << "Message queue deleted successfully." << std::endl; return EXIT_SUCCESS; } ``` #### 解析代码功能 - **创建/打开消息队列**: 使用 `mq_open` 函数创建或打开名为 `/my_message_queue` 的消息队列。如果队列不存在,则创建之;如果已存在,则直接打开。 - **获取消息队列状态**: 利用 `mq_getattr` 函数查询当前消息队列的各种属性,并将其打印出来[^2]。 - **关闭与删除消息队列**: 使用 `mq_close` 和 `mq_unlink` 分别完成关闭和删除消息队列的任务[^2]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值