赞
踩
RabbitMQ是比较流行的消息中间件,最近在使用这个消息队列,就抽空把此潦草的学习了一下:
RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件)。
RabbitMQ服务器是用Erlang语言编写的,而集群和故障转移是构建在开放电信平台框架上的。
所有主要的编程语言均有与代理接口通讯的客户端库。(百度百科)
先笼统的说一下吧:
ConnectionFactory:消息中间件的对象
Connection:创建链接
Channel:会话和模型
Queue:队列的对象
ExChange:交换器
RoutingKey:路由钥匙
如果要使用ExChange和RoutingKey时要Queue创建相关的链接,要不消息就会放进无效的队列中,在我们的站点上可以进行配置,下面看一下发送的代码:
- static void Main(string[] args)
- {
- var factory = new ConnectionFactory();
- factory.HostName = "127.0.0.1";//主机名
- factory.UserName = "";//默认用户名
- factory.Password = "";//默认密码
-
- using (var connection = factory.CreateConnection())
- using (var channel = connection.CreateModel())
- {
- channel.QueueDeclare("HelloQueue",true,false,false,null);
- channel.ExchangeDeclare("HelloExchange", "direct", false, false, null);
-
- for (int i = 0; i < 1000; i++)
- {
- string message = "Hello World";
- var body = Encoding.UTF8.GetBytes(message);
- channel.BasicPublish("HelloExchange", "HelloRouting", null, body); //开始传递
- Console.WriteLine("已发送: {0}", message + DateTime.Now + Environment.NewLine);
- Thread.Sleep(1000);
- }
-
-
- }
-
- Console.WriteLine(" 点击 [enter] 结束本次对话。");
-
- Console.ReadLine();
- }
接收消息的代码:
- static void Main(string[] args)
- {
-
- var factory = new ConnectionFactory();
- factory.HostName = "127.0.0.1";//主机IP
- factory.UserName = "";//用户名
- factory.Password = "";//密码
- factory.Port = 5672;
- using (var connection = factory.CreateConnection())
- {
- using (var channel = connection.CreateModel())
- {
- var consumer = new EventingBasicConsumer(channel);
- channel.BasicConsume("HelloQueue", true, consumer);
- consumer.Received += (model, ea) =>
- {
- var body = ea.Body;
- var message = Encoding.UTF8.GetString(body);
- Console.WriteLine("已接收: {0}", message);
- };
-
- }
- }
- Console.WriteLine(" 点击 [enter] 结束本次对话。");
- Console.ReadLine();
- }
记录一下rabbitmq的基本操作,如果还需要更复杂的生产环境就需要进一步去学习了,研究了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。