jmstemplate 发送文本消息的写法
第一种手动构造msg的话不需要做特殊处理,但是很麻烦
0 1 2 3 4 5 6 7 8 |
private void sendMessage(String msg) { jmsTemplate.send(new ActiveMQQueue(someQueueName), new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage(msg); } }); } |
调用方写法
0 1 2 3 |
SomeClass someObject = new SomeClass(); Gson gson = new Gson(); sendMessage(gson.toJson(someObject)); |
第二种自动构造msg需要在注入bean的时候指定msgConverter,写法简洁但是需要注意不要做第手动转换
0 1 2 3 4 5 6 7 |
@Bean(name = "jmsTemplate") public JmsTemplate getJmsTemplate() { ConnectionFactory connectionFactory = getConnectionFactory(); JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory); jmsTemplate.setMessageConverter(jacksonJmsMessageConverter()); return jmsTemplate; } |
0 1 2 3 |
private void sendMessage(Object msg) { jmsTemplate.convertAndSend(someQueueName, msg); } |
调用方写法
0 1 2 3 4 |
SomeClass someObject = new SomeClass(); // 这么写会出问题!!!!不要问我怎么知道的,手动微笑 // sendMessage(gson.toJson(someObject)) sendMessage(someObject) |
1 Comments
不错不错!内容感觉好极了!