easyNetq demo
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了easyNetq demo相关的知识,希望对你有一定的参考价值。
本demo包含一个类库,2个console程序
1.新建类库 MQHelper,控制台程序 consumer和proc ,控制台程序引用MQHelper
2.使用nuget安装easynwtq 和rabbitmq.client.dll ,执行Install-Package EasyNetQ -Version 1.1.3.500
会自动安装 easynwtq和依赖项rabbitmq.client.dll
3.MQHelper
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EasyNetQ; namespace MQHelper { public class MQManage { /// <summary> /// 发送消息 /// </summary> public static void Publish(MyMessage msg) { //// 创建消息bus IBus bus = RabbitHutch.CreateBus("host=192.168.1.1:5672;virtualHost=as;username=123;password=123"); try { bus.Publish(msg, x => x.WithTopic(msg.MessageRouter)); } catch (EasyNetQException ex) { //处理连接消息服务器异常 } bus.Dispose();//与数据库connection类似,使用后记得销毁bus对象 } /// <summary> /// 接收消息 /// </summary> /// <param name="msg"></param> public static void Subscribe(MyMessage msg) { //// 创建消息bus IBus bus = RabbitHutch.CreateBus("host=192.168.1.1:5672;virtualHost=as;username=123;password=123"); try { bus.Subscribe<MyMessage>(msg.MessageRouter, message => Console.WriteLine(message.MessageBody), x => x.WithTopic(msg.MessageRouter)); } catch (EasyNetQException ex) { //处理连接消息服务器异常 } } } public class MyMessage { public string MessageID { get; set; } public string MessageTitle { get; set; } public string MessageBody { get; set; } public string MessageRouter { get; set; } } }
4.proc 生产程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace proc { class Program { static void Main(string[] args) { Console.WriteLine("proc2"); //// 创建消息bus while (true) { MQHelper.MQManage.Publish(new MQHelper.MyMessage { MessageID = "2", MessageRouter = "ro2", MessageBody ="当前时间="+DateTime.Now.ToString(), MessageTitle = "title" + DateTime.Now }); Thread.Sleep(3000); } } } }
5.consumer 消费程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace consumer { class Program { static void Main(string[] args) { Console.WriteLine("consumer2"); //// 创建消息bus MQHelper.MQManage.Subscribe(new MQHelper.MyMessage { MessageID = "2", MessageRouter = "ro2" //MessageBody=DateTime.Now.ToString(), //MessageTitle="title"+DateTime.Now }); } } }
6.先bin/debug 里先打开 consumer.exe ,再打开proc.exe 就能看到效果了
以上是关于easyNetq demo的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 EasyNetQ / RabbitMQ 进行错误处理
EasyNetQ-用于使用 RabbitMQ 的 .NET API开源的工具库