rabbitmq的使用
1安装rabbitmq先要安装erlang,这里就不演示了(两个版本要适应)
2nuget包(RabbitMQ.Client)
3appsetting配置(这里选择rabbitmq默认的)
"RabbitMQ": { "MessageMQUserName": "guest", //我选的是默认的用户,也可以自行添加,添加新用户时,要给用户添加权限 "MessageMQPassword": "guest", "MessageMQHostName": "5672", "MessageMQQueueName": "123456" }
4配置类用来接收appsetting中的
public class RabbitMQDto { public string MessageMQUserName { get; set; } public string MessageMQPassword { get; set; } public string MessageMQHostName { get; set; } public string MessageMQQueueName { get; set; } }
5注入
services.Configure<RabbitMQDto>(Configuration.GetSection("RabbitMQ"));
6控制器使用(这里没有封装了,直接来用)
private readonly RabbitMQDto _rabbitMQDto; public DemoController(IOptionsMonitor<RabbitMQDto> rabbitMQDto) { _rabbitMQDto = rabbitMQDto.CurrentValue; } /// <summary> /// 发送消息 /// </summary> /// <returns></returns> [HttpGet] public void RabbitMQ() { var a = _rabbitMQDto.MessageMQUserName; ConnectionFactory factory = new ConnectionFactory { UserName = _rabbitMQDto.MessageMQUserName, Password = _rabbitMQDto.MessageMQPassword, HostName = "localhost", Port = 5672, }; using (IConnection con = factory.CreateConnection())//创建连接对象 { using (IModel channel = con.CreateModel())//创建连接会话对象 { //声明一个队列 channel.QueueDeclare( queue: _rabbitMQDto.MessageMQQueueName,//消息队列名称 durable: false,//是否缓存 exclusive: false, autoDelete: false, arguments: null ); for (int i = 0; i < 10; i++) { Console.WriteLine("消息内容:"); var message = "233"; //消息内容 byte[] body = Encoding.UTF8.GetBytes(message); //发送消息 channel.BasicPublish(exchange: "", routingKey: _rabbitMQDto.MessageMQQueueName, basicProperties: null, body: body); Console.WriteLine("成功发送消息:" + message); } } } } //接收消息 public void GetInformationFromRabbitMQ() { Console.WriteLine("Start"); IConnectionFactory connectionFactory = new ConnectionFactory { HostName = "localhost", Port = 5672, UserName = _rabbitMQDto.MessageMQUserName, Password = _rabbitMQDto.MessageMQPassword }; using (IConnection conn = connectionFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { channel.QueueDeclare( queue: _rabbitMQDto.MessageMQQueueName, durable: false, //是否缓存 exclusive: false, autoDelete: false, arguments: null ); //创建消费者对象 var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { //byte[] message = ea.Body;//接受到的消息 var message = Encoding.UTF8.GetString(ea.Body.ToArray()); Console.WriteLine("接受到信息为:" + message); }; //消费者开启监听 channel.BasicConsume(queue : _rabbitMQDto.MessageMQQueueName, autoAck: true, consumer: consumer); Console.ReadKey(); } } }