C#集成rabbitmq发消息

本文介绍了一个使用RabbitMQ进行消息推送的方法。通过C#客户端库RabbitMQ.Client,实现了向指定队列发送持久化消息的功能。文章提供了完整的代码示例,包括连接配置、队列声明及消息发布。

引用RabbitMQ.Client.dll

 

//参数:message  消息     

        //      hostName  请求服务器地址,默认本机
        //      QueueName 队列名称
        //      port  请求端口号 默认 5672
        public static bool Push(string message, string hostName = "localhost", string QueueName = "push_queue", int port = 5672)
        {
            if (hostName == null) { hostName = "localhost"; }
            if (QueueName == null) { QueueName = "push_queue"; }
            if (port == null) { port = 5672; }
            try
            {
                ConnectionFactory factory = new ConnectionFactory(); 
                factory.HostName = hostName;
                factory.Port = port;

                IConnection conn = factory.CreateConnection();

                IModel channel = conn.CreateModel();

                //在MQ上定义一个持久化队列
                channel.QueueDeclare(QueueName, true, false, false, null);

                byte[] bytes = Encoding.UTF8.GetBytes(message);

                //设置消息持久化
                IBasicProperties properties = channel.CreateBasicProperties();
                properties.DeliveryMode = 2;
                channel.BasicPublish("", QueueName, properties, bytes);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值