C#使用rabbitmq (简单例子)

首先在visual studio项目里面用nuget工具加入 easyNetQ DLL 

然后做一个help类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EasyNetQ;
using EasyNetQ.Topology;

namespace ConsoleAppPublish
{
    public class MQHelp
    {
        public string IPAddress { get; set; }
        public string VirtualHost { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string ExchangeName { get; set; }
        public string RouteName { get; set; }
        public string QueueName { get; set; }
        public MQSendEnum SendEnum { get; set; } 

        private IBus bus = null;

        public MQHelp(string ip, string vHost, string user, string pwd, string exchange, string rout, string queue, MQSendEnum em)
        {
            this.IPAddress = ip;
            this.VirtualHost = vHost;
            this.Username = user;
            this.Password = pwd;
            this.ExchangeName = exchange;
            this.RouteName = rout;
            this.QueueName = queue;
            this.SendEnum = em;

            try
            {
                this.bus = RabbitHutch.CreateBus(GetMqConnection());

                if (string.IsNullOrEmpty(queue) == false)
                {
                    bus.Advanced.QueueDeclare(queue);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private string GetMqConnection()
        {
            string conn = string.Format("host={0};virtualHost={1};username={2};password={3}",
                IPAddress, VirtualHost, Username, Password);

            return conn;
        }

        public void SendMsg(string msg)
        {
            try
            {
                //MyMessage msgOBJ = new MyMessage() { Text=msg };
                var message = new EasyNetQ.Message<object>(msg);

                IExchange ex = null;
                //判断推送模式
                if (this.SendEnum == MQSendEnum.Direct)
                {
                    ex = bus.Advanced.ExchangeDeclare(this.ExchangeName, ExchangeType.Direct);
                }
                if (this.SendEnum == MQSendEnum.Fanout)
                {
                    //广播订阅模式
                    ex = bus.Advanced.ExchangeDeclare(this.ExchangeName, ExchangeType.Fanout);
                }
                if (this.SendEnum == MQSendEnum.Topic)
                {
                    //主题路由模式
                    ex = bus.Advanced.ExchangeDeclare(this.ExchangeName, ExchangeType.Topic);
                }

                //发送
                this.bus.Advanced.Publish(ex, this.RouteName, false, message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public void ReceiveMsg()
        {
            try
            {
                this.bus.PubSub.Subscribe<object>("", m => {
                    Console.WriteLine(m.ToString());
                    //LogHelp.Info(m.ToString());
                } ,f => {
                    f.WithQueueName(this.QueueName);
                } );
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


    }

    public enum MQSendEnum
    {
        Direct = 1,   //推送模式
        Fanout = 2,   //订阅模式
        Topic = 3     //主题路由模式
    }
     

}

然后在控制台里面发送  或者 接收MQ 消息:

   class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("MQ test");
 

            MQHelp mq = new MQHelp("10.10.10.10", "testhost", "admin", "adminPWD", "amq.topic", "orderTEST", "qTEST", MQSendEnum.Topic);
            mq.SendMsg("hello123"); 
            mq.ReceiveMsg();



            Console.WriteLine("end Program");
            Console.ReadLine();
        }
    }

### C# 使用 RabbitMQ 实现消息队列 示例教程 #### 安装 RabbitMQ 客户端库 为了在C#项目中使用RabbitMQ,需要先安装适用于.NET的RabbitMQ客户端库。可以通过NuGet包管理器轻松完成此操作[^2]。 ```shell Install-Package RabbitMQ.Client ``` #### 创建生产者应用程序 创建一个新的控制台应用作为生产者,负责向消息队列发送消息。以下是完整的代码示例: ```csharp using System; using System.Text; using RabbitMQ.Client; class Producer { public static void Main() { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); string message = "Hello World!"; var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body); Console.WriteLine(" [x] Sent {0}", message); } Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } } ``` 这段程序会连接到本地运行的RabbitMQ服务器,并声明名为`hello`的消息队列。接着它将一条字符串形式的信息转换成字节数组并发布给该队列[^1]。 #### 构建消费者应用程序 同样地,在另一个新的控制台项目中编写接收来自上述队列消息的应用逻辑。这里展示了一个基本的例子: ```csharp using System; using System.Text; using RabbitMQ.Client; using RabbitMQ.Client.Events; class Consumer { public static void Main() { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); }; channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } } } ``` 在这个例子中,当接收到新消息时就会触发事件处理函数,从而打印出所接受的数据内容。注意这里的自动确认模式(`autoAck`)被设置为true意味着一旦消息被成功传递就立即告知服务端删除这条记录;如果希望更精细地控制这一过程,则应将其设为false并在适当时候手动执行确认动作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值