1、简单设置场景
需要一个日志系统,使用RabbitMQ推送
日志等级要求如下:
Log levels
debug、info、warning、error、none
2、代码实现
1)生产者
//基础配置 ConnectionFactory factory = new ConnectionFactory() { HostName = "10.123.44.12", UserName = "datamip", Password = "datamip" }; //第一步:创建connection using (var connection = factory.CreateConnection()) { //第二步:创建channel using (var channel = connection.CreateModel()) { //第三步:创建exchange channel.ExchangeDeclare("myexchange", ExchangeType.Direct, true, false, null); //第四步:发布消息,直接绑定对应的routingkey for (int i = 0; i < 100; i++) { var msg = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", i, "你好")); var level = i % 13 == 0 ? "info" : "error";//方便演示 channel.BasicPublish("myexchange", level, basicProperties: null, body: msg); } } } Console.WriteLine("生产成功!"); Console.ReadKey();
2)消费者
i:info消费者
//创建连接工厂 ConnectionFactory factory = new ConnectionFactory { UserName = "datamip",//用户名 Password = "datamip",//密码 HostName = "10.123.44.12"//rabbitmq ip }; //第一步:创建connection using (var connection = factory.CreateConnection()) { //第二步:创建channel using (var channel = connection.CreateModel()) { //第三步:生明交换机 channel.ExchangeDeclare("myexchange", ExchangeType.Direct, true, false, null); //第四步:声明队列,绑定交换机 channel.QueueDeclare("log_else",true,false,false,null); //绑定当前需要消费的routingkey channel.QueueBind("log_else", "myexchange", "info", null); //处理消息 EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender,e)=> { var msg = Encoding.UTF8.GetString(e.Body.ToArray()); Console.WriteLine(msg); }; //消费 channel.BasicConsume("log_else", true, consumer); Console.ReadKey(); } }
ii:error消费者
//创建连接工厂 ConnectionFactory factory = new ConnectionFactory { UserName = "datamip",//用户名 Password = "datamip",//密码 HostName = "10.123.44.12"//rabbitmq ip }; //第一步:创建connection using (var connection = factory.CreateConnection()) { //第二步:创建channel using (var channel = connection.CreateModel()) { //第三步:生明交换机 channel.ExchangeDeclare("myexchange", ExchangeType.Direct, true, false, null); //第四步:声明队列,绑定交换机 channel.QueueDeclare("log_error", true, false, false, null); //绑定当前需要消费的routingkey channel.QueueBind("log_error", "myexchange", "error", null); //处理消息 EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, e) => { var msg = Encoding.UTF8.GetString(e.Body.ToArray()); Console.WriteLine(msg); }; //消费 channel.BasicConsume("log_error", true, consumer); Console.ReadKey(); } }
3、图形解释