demo下载:testjms-request-reply.zip
当发起请求时,调用session.createTemporaryQueue()创建一个临时的Queue,调用requestMessage.setJMSReplyTo(responseQueue)将临时Queue和requestMessage关联,这个动作已经被jmsTemplate.sendAndReceive()方法封装了,调用该方法就会返回responseMessage.当应答端收到requestMessage,调用session.createProducer()创建一个messageProducer,调用session.createTextMessage()创建一个message,使用messageProducer.send(requestMsg.getJMSReplyTo(), replyMsg),通过请求中的ReplyTo通道将响应返回给请求端。
如果在请求端你想知道某个响应是和哪个请求关联的。那么我们可以给Message对象添加CorrelationID头,使用jmsTemplate.sendAndReceive()方法的大致代码如下(参考:cn.javacoder.testjms_send.App):
1 2 3 4 5 6 7 8 9 10 |
Message replyMsg = jmsTemplate.sendAndReceive("test.queue", new MessageCreator() { public Message createMessage(Session session) throws JMSException { ObjectMessage objMsg = session.createObjectMessage(user); String correlationID = UUID.randomUUID().toString(); System.out.println("correlationID:" + correlationID); objMsg.setJMSCorrelationID(correlationID); return objMsg; } }); |
jmsTemplate 没有提供类似receiveAndReply()的方法,所以需要我们自己编码来实现。大致的代码如下(参考:cn.javacoder.testjms_receive.Reply):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(null); consumer = session.createConsumer(destination); Message msg = consumer.receive(); ObjectMessage objMsg = (ObjectMessage)msg; User user = (User)objMsg.getObject(); System.out.println("receive user:"+ user.getUsername()); TextMessage replyMsg = session.createTextMessage(); replyMsg.setJMSCorrelationID(msg.getJMSCorrelationID()); replyMsg.setText("reply message"); producer.send(msg.getJMSReplyTo(), replyMsg); |
1)http://activemq.apache.org/how-should-i-implement-request-response-with-jms.html
2)《ActiveMQ in Action》
Posted in: spring practise | Tags: JMS, spring
Comments are closed.