rabbitmq是什么及如何安装就不再赘述,百度一下就知道了,只是在配置方面要多加注意。
话不多说,先直接上一个简示例代码
发送端:
connectionfactory factory = new connectionfactory { hostname = "hostname", username = "root", password = "root001", virtualhost = "hostserver" };
using (iconnection conn = factory.createconnection())
{ using (imodel im = conn.createmodel())
{
im.exchangedeclare("rabbitmq_route", exchangetype.direct);
im.queuedeclare("rabbitmq_query", false, false, false, null);
im.queuebind("rabbitmq_query", "rabbitmq_route", exchangetype.direct, null);
for (int i = 0; i < 1000; i++)
{ byte[] message = encoding.utf8.getbytes("hello lv");
im.basicpublish("rabbitmq_route", exchangetype.direct, null, message);
console.writeline("send:" + i);
}
}
}
接收端:
connectionfactory factory = new connectionfactory { hostname = "hostname", username = "root", password = "root001", virtualhost = "hostserver" };
using (iconnection conn = factory.createconnection())
{ using (imodel im = conn.createmodel())
{ while (true)
{
basicgetresult res = im.basicget("rabbitmq_query", true);
if (res != null)
{
console.writeline("receiver:"+utf8encoding.utf8.getstring(res.body));
}
}
}
}
发送端一次性发送一千条,发送过程很快,接收时相对要慢一些。
上述demo只限一个接收着,那相同的发送量,多个接收者会出现什么情况,添加一个新的接收端,直接复制demo中接收端即可。
附上运行结果:
可以看到,在两个接收端同时运行时,rabbitmq 会按顺序的分发每个消息。当每个收到确认后,会将该消息删除,然后将下一个分发到下一个接收者,主要是因为rabbitmq的循环分发机制。
上面简单说了一下,在多个接收者时,因为循环分发的原因,消息几乎是两个接收端对分的。
那么如何将相同的消息分发到多个接收端。
对发送端代码进行修改:
connectionfactory factory = new connectionfactory { hostname = "hostname", username = "root", password = "root001", virtualhost = "host" };
using (iconnection conn = factory.createconnection())
{ using (imodel im = conn.createmodel())
{
im.exchangedeclare("rabbitmq_route_fanout", exchangetype.fanout);// 路由
int i = 0;
while (true)
{
thread.sleep(1000);
++i;
byte[] message = encoding.utf8.getbytes(i.tostring());
im.basicpublish("rabbitmq_route_fanout", "", null, message);
console.writeline("send:" + i.tostring());
}
}
}
与上种方式比较,会发现在代码注释后面少两段代码,在设置了fanout方式后,不需要再指定队列名称。停一秒是为了方便看结果,以免刷新太快。
再来看看接收端代码:
connectionfactory factory = new connectionfactory { hostname = "hostname", username = "root", password = "root001", virtualhost = "host" };
using (iconnection conn = factory.createconnection())
{ using (imodel im = conn.createmodel())
{
im.exchangedeclare("rabbitmq_route_fanout", exchangetype.fanout);
var queueok = im.queuedeclare();//1
im.queuebind(queueok.queuename, "rabbitmq_route_fanout", "");//2
var consumer = new queueingbasicconsumer(im);//3
im.basicconsume(queueok.queuename, true, consumer);//4
while (true)
{var _result = (basicdelivereventargs)consumer.queue.dequeue();//5
var body = _result.body;
var message = encoding.utf8.getstring(body);
console.writeline("received:{0}", message);
}
}
当一个新的接收端连接时(消费者),需要一个申报一个新的队列,注释1处代码,rabbitmq在申报队列时,如果不指定名称会自动生成一个,这还是不错的。
两个接收端时运行结果,符合预期。
至于广播方式有什么不好之处,亲自运行下就知道了.
以上就是c#中关于rabbitmq应用的图文代码详解 的详细内容。
