首页 > 代码库 > easyNetq demo
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。