消费者:
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 会匹配上