rabbitmq 一个java 开源的消息中间件,可以用来对应用之间的调用解耦,比如说,我要对登陆事件进行多种操作(记录日志、更新某些信息)。这些应用依赖登陆事件,但登陆本身并不对这些应用有依赖,可以通过消息中间件的方式进行解耦。
由对登陆事件感兴趣的应用系统订阅消息,对消息处理,完成业务需求,同时对各系统解耦。
rabbitmq 的介绍以及教程网上有,需要的可以百度,这里仅上两端带注释的代码
//生产者
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.22.111");
factory.setUsername("guest");
factory.setPassword("guest");
//创建连接
Connection connection = factory.newConnection();
//创建channel 所有的消息操作基于channel
Channel channel = connection.createChannel(10);
//声明一个exchange topic 类型
channel.exchangeDeclare("crm.topic", "topic",true,false,false,null);
//声明一个队列
channel.queueDeclare("app.login.user", true, false, false, null);
//将queue 与exchange 绑定
channel.queueBind("app.login.user", "crm.topic", "app.login.user");
//发送消息,指定与exchange & routingKey
channel.basicPublish("crm.topic", "app.login.user", null, "sxxxxxxxxxx".getBytes());
channel.close();
connection.close();
消费者
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.22.111");
factory.setUsername("guest");
factory.setPassword("guest");
//创建连接
Connection connection = factory.newConnection();
Channel channel = connection.createChannel(10);
//声明一个队列
channel.queueDeclare("crmcommon.login.user", true, false, false, null);
//将queue 与exchange 绑定
channel.queueBind("crmcommon.login.user", "crm.topic", "crmcommon.login.user");
//消费
GetResponse r = channel.basicGet("crmcommon.login.user", true);
System.out.println(new String(r.getBody()));
channel.close();
connection.close();
以上是一个简单的生产者,一个简单的消费者。
下面是使用spring整合的配置
username="${amqp.rabbit.username}"
password="${amqp.rabbit.password}"
/>
connection-factory="connectionFactory"
message-converter="messageConverter">
可以看到spring 配置也是要配置上面代码的基本元素,spring 同时提供了一下封装类,对消息的转换,操作模板等。