在.net core控制台安装
Install-Package EasyNetQ
一:定义公共消息类
namespace Messages { public class TextMessage { public string Text { get; set; } } }
二: 发布者代码
using System; using EasyNetQ; using Messages; namespace Publisher { class Program { static void Main(string[] args) { using (var bus = RabbitHutch.CreateBus("host=localhost")) { var input = ""; Console.WriteLine("Enter a message. 'Quit' to quit."); while ((input = Console.ReadLine()) != "Quit") { bus.Publish(new TextMessage { Text = input }); } } } } }
三: 订阅者代码
using System; using EasyNetQ; using Messages; namespace Subscriber { class Program { static void Main(string[] args) { using (var bus = RabbitHutch.CreateBus("host=localhost")) { bus.Subscribe<TextMessage>("test", HandleTextMessage); Console.WriteLine("Listening for messages. Hit <return> to quit."); Console.ReadLine(); } } static void HandleTextMessage(TextMessage textMessage) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Got message: {0}", textMessage.Text); Console.ResetColor(); } } }
同时启动两者控制台代码