简介
可以参考官网:http://www.rabbitmq.com/
配置文件
配置文件中的属性解释,点击查看
application-rabbitmq.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:rabbitMq.properties" ignore-unresolvable="false" />
<!--创建一个broker连接(代理)。连接rabbit cache-mode="CONNECTION"tcp连接 cache-mode="CHANNEL"channel连接-->
<rabbit:connection-factory id="connectionFactory" channel-cache-size="20" host="${rabbitmq.host}"
cache-mode="CONNECTION" port="5672" username="${rabbitmq.username}"
password="${rabbitmq.password}" connection-timeout="1000" />
<!--声明一个RabbitAdmin管理exchange,queue,bindings-->
<rabbit:admin connection-factory="connectionFactory" />
<!--消息监听的Message里的body 被格式化为json 可以转为json格式获取信息-->
<bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"/>
<!--消息通道 消息载体 -->
<rabbit:queue id="yue_xia_du_zhuo" name="parentQueue" durable="true" auto-delete="false" exclusive="false"/>
<!--exchange消息交换机 他指定消息按照什么规则,路由到什么queque-->
<rabbit:direct-exchange name="tell_all_exchange" auto-delete="false" durable="true" >
<rabbit:bindings>
<!--绑定queue 跟 exchange-->
<rabbit:binding queue="yue_xia_du_zhuo" key="yue_xia_du_zhuo" ></rabbit:binding>
</rabbit:bindings>
</rabbit:direct-exchange>
<!--声明一个模板访问broker-->
<rabbit:template exchange="tell_all_exchange" connection-factory="connectionFactory" id="tellAllExchange" />
<!--监听容器-->
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto" >
<rabbit:listener ref="parentListener" queues="parentQueue" />
</rabbit:listener-container>
MqProductManageImpl
消息生产者,控制层通过注入生产者,传入queue,跟消息载体的Map,生产者根据queue进行路由
/**
* Created by zhanghe
* 2018/3/15.
*/
@Component
public class MqProductManageImpl implements IMqProductManager {
@Autowired
// 必须在xml 文件中 <rabbit:template>中声明才可以注入
@Qualifier("tellAllExchange")
AmqpTemplate tellAllTemplate;
/**
*
* @param queueKey 管道key,exchange通过queuekey 连接到queue
* @param object 传送的信息 一般都是一个Map
*/
@Override
public void sendData(String queueKey, Object object) {
switch (queueKey) {
case "yue_xia_du_zhuo":
tellAllTemplate.convertAndSend(queueKey, object);
break;
case "si_gu_xiang":
tellAllTemplate.convertAndSend(queueKey, object);
break;
default:
break;
}
}
}
ParentListener
/**
* Created by zhanghe
* 2018/3/14.
*/
@Component
public class ParentListener implements MessageListener{
private static final Logger LOGGER = LoggerFactory.getLogger(ParentListener.class);
// 如果不继承MessageListener 则需要在xml中配置当前的method 比如:receiveMsg
// public void receiveMsg(Message message){
// try {
// String msg = new String(message.getBody(), "UTF-8");
// JSONObject jsonObject = JSONObject.parseObject(msg);
// String dyc = jsonObject.getString("dui_ying_cheng_san_ren");
// System.out.println("message"+":"+message+"举杯邀明月\r\ndyc:"+dyc);
//
// } catch (UnsupportedEncodingException e) {
// LOGGER.error("解码异常,errorInfo----{}-----",e);
// }
// }
@Override
public void onMessage(Message message) {
try {
//获取Message中的body(消息) 然后转码,由于xml文件中的jsonMessageConverter 这里为json格式
String msg = new String(message.getBody(), "UTF-8");
JSONObject jsonObject = JSONObject.parseObject(msg);
String dyc = jsonObject.getString("dui_ying_cheng_san_ren");
System.out.println("message"+":"+message+"举杯邀明月\r\ndyc:"+dyc);
} catch (Exception e) {
LOGGER.error("解码异常,errorInfo----{}-----",e);
}
}
}
在控制层注入生产者,然后调用并发送信息
@ResponseBody
@RequestMapping(value = "/sendSentence")
public RspVo sendSentence(){
Map<String,Object> sentenceMap = new HashMap<>();
sentenceMap.put("dui_ying_cheng_san_ren","对影成三人");
mqProductManager.sendData(SystemComponent.YUE_XIA_DU_ZHO,sentenceMap);
return RspVo.success("success");
}
看看实际运行情况
- 进入控制层
- 控制层调用生产者
- 直接返回控制层
- 异步执行监听中的方法,失败报错则会重新发送消息
如果在xml中不设置jsonMessageConverter,然后再onMessage中用JSONObject接受,则会报错
Caused by: com.alibaba.fastjson.JSONException: syntax error
有不正确的地方欢迎指正
个人原创,转载请标明出处