RabbitMQ通过Exchange.topic 对routingkey 进行正则表达式匹配

消费者:

 static void Main(string[] args)
{
ConnectionFactory factory = new ConnectionFactory()
{
HostName = "192.168.254.40",
UserName = "admin",
Password = "admin",
}; //第一步:创建connection
var connection = factory.CreateConnection(); //第二步:创建一个channel
var channel = connection.CreateModel(); //第三步:申明交换机【因为rabbitmq已经有了自定义的ampq default exchange】
channel.ExchangeDeclare("mytopicexchange", ExchangeType.Topic, true, false, null); //第四步:创建一个队列(queue)
channel.QueueDeclare("mytopicqueue", true, false, false, null); //将queue绑定到exchange之上。。。。
channel.QueueBind("mytopicqueue", "mytopicexchange", "*.com", null); EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, e) =>
{
var msg = Encoding.UTF8.GetString(e.Body); Console.WriteLine(msg);
}; channel.BasicConsume("mytopicqueue", true, consumer); Console.WriteLine("consumer1 端启动完毕!!!"); Console.Read();
}

生产者:

static void Main(string[] args)
{
ConnectionFactory factory = new ConnectionFactory()
{
HostName = "192.168.254.40",
UserName = "admin",
Password = "admin",
}; //第一步:创建connection
var connection = factory.CreateConnection(); //第二步:创建一个channel
var channel = connection.CreateModel(); for (int i = ; i < ; i++)
{
var msg = Encoding.UTF8.GetBytes(string.Format("{0} :{1}", i, "你好")); var routingKey = i % == ? "a.com" : "*.cn"; //第五步:发布消息
channel.BasicPublish("mytopicexchange", routingKey: routingKey, basicProperties: null, body: msg); Console.WriteLine(i);
}
}

当生产者routingkey 为a.com,消费者*.com 会匹配上

上一篇:十八、.net core(.NET 6)搭建ElasticSearch(ES)系列之使用Logstash通过Rabbitmq接收Serilog日志到ES


下一篇:Logback 整合 RabbitMQ 实现统一日志输出