RabbitMQ EasyNetq 用法

EasyNETQ帮助类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class MQHelper
    {
        /// <summary>
        /// 发送消息
        /// </summary>
        public static void Publish(Message msg)
        {
            //// 创建消息bus
            IBus bus = BusBuilder.CreateMessageBus();
 
            try
            {
                bus.Publish(msg, x => x.WithTopic(msg.MessageRouter));
            }
            catch (EasyNetQException ex)
            {
                System.Console.WriteLine("发送消息:" + ex.Message);
                //处理连接消息服务器异常
            }
 
            bus.Dispose();//与数据库connection类似,使用后记得销毁bus对象
        }
 
        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="msg"></param>
        public static void Subscribe(Message msg, IProcessMessage ipro)
        {
            //// 创建消息bus
            IBus bus = BusBuilder.CreateMessageBus();
 
            try
            {
                bus.Subscribe<Message>(msg.MessageRouter, message => ipro.ProcessMsg(message), x => x.WithTopic(msg.MessageRouter));
 
                System.Console.WriteLine("订阅消息成功");
            }
            catch (EasyNetQException ex)
            {
                System.Console.WriteLine("订阅消息失败:" + ex.Message);
            }
 
            //与数据库connection类似,使用后记得销毁bus对象
        }
    }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class BusBuilder
   {
       public static IBus CreateMessageBus()
       {
           //消息服务器连接字符串
           var connectionString = ConfigurationManager.ConnectionStrings["RabbitMQ"];
           if (connectionString == null || connectionString.ConnectionString == string.Empty)
           {
               throw new Exception("messageserver connection string is missing or empty");
           }
           return RabbitHutch.CreateBus(connectionString.ConnectionString);
       }
 
         
   }

 

1
2
3
4
5
6
public interface IProcessMessage
{
    void ProcessMsg(Message msg);
 
    void Notice();
}

 

1
2
3
4
5
6
7
8
9
10
public class Message
{
    public string MessageID { get; set; }
 
    public string MessageTitle { get; set; }
 
    public string MessageBody { get; set; }
 
    public string MessageRouter { get; set; }
}

 

posted @   桃花雪  阅读(517)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示