消息队列-rabbitmq
//生产者 using System; using System.Text; using Microsoft.AspNetCore.Mvc; using RabbitMQ.Client; namespace App.Controllers { public class ProducerController:Controller { public void SendMessage(string message) { var factory = new ConnectionFactory(){HostName = "localhost"}; using(var connection = factory.CreateConnection()) { using(var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "demo", durable: true, exclusive: false, autoDelete: false, arguments: null); var body = Encoding.UTF8.GetBytes(message); var properties = channel.CreateBasicProperties(); properties.Persistent = true;//持久化设置,配合durable: true可以保证队列挂了之后队列中的消息不回丢失 channel.BasicPublish(exchange: "", routingKey: "demo", basicProperties: properties, body: body); } } } } }
//消费者 using System; using System.Text; using System.Threading; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace consumer { class Program { static void Main(string[] args) { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "demo", durable: true, exclusive: false, autoDelete: false, arguments: null); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);//一次接受一个消息来消费 var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [2222222x] Received {0}", message); Thread.Sleep(8000); channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: "demo", autoAck: false, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadKey(); } } } }