依赖注入
var connectionConfiguration = new ConnectionConfiguration { Hosts = new List<HostConfiguration> { new HostConfiguration { Host = hostName, Port = Convert.ToUInt16(mqport) } }, Port = Convert.ToUInt16(mqport), VirtualHost = "/", UserName = userName, Password = password }; services.AddSingleton(RabbitHutch.CreateBus(connectionConfiguration, x => { }));
接收消息
IBus对象通过依赖注入获取
var exchange = _bus.Advanced.ExchangeDeclare("ExchangeNAME", ExchangeType.Topic); var nickNameQu = _bus.Advanced.QueueDeclare("queuename"); _bus.Advanced.Bind(exchange, nickNameQu, "RouterKey1"); _bus.Advanced.Bind(exchange, nickNameQu, "RouterKey2"); _bus.Advanced.Consume(nickNameQu, (data, properties, info) => { var msg = Encoding.UTF8.GetString(data); });
消息发送
var exchange = this.Bus.Advanced.ExchangeDeclare("ExchangeNAME", ExchangeType.Topic); this.Bus.Advanced.Publish(exchange, "RouterKey1", false, new MessageProperties(), Encoding.UTF8.GetBytes("消息内容"));