(八):JMSReplyTo

本文展示了一个使用Java消息服务(JMS)实现消息发送、接收及回复的示例。发送者将包含特定内容的消息发送到第一个队列,接收者收到消息后会向第二个队列发送回复消息。最终通过消费者从第二个队列读取消息并打印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在下面的例子中,首先创建两个Queue,发送者给一个Queue发送,接收者接收到消息之后给另一个Queue回复一个Message,然后再创建一个消费者来接受所回复的消息。[/size]
/**
*
*/
package reply;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

/**
* Producer send a message with the content "Josh", The receiver will reply
* to the message after received the message, the content is "Hello, Josh",
* Finally create another consumer on the second queue and print the content.
* @author Wang Sheng(Josh)
*
*/
public class MessageSendReceiveAndReply {

/**
* @param args
*/
public static void main(String[] args) throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();

Connection connection = factory.createConnection();
connection.start();

// Send the message to the queue
Queue queue = new ActiveMQQueue("Josh_ReceiveQueue");

// Reply the message to the queue
Queue replyQueue = new ActiveMQQueue("Josh_ReplyQueue");

final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

// Create a message and set the JMSReplyTo with replyQueue
Message message = session.createTextMessage("Josh");
// Define where will the message reply to
message.setJMSReplyTo(replyQueue);

MessageProducer producer = session.createProducer(queue);
producer.send(message);

// The receiver of the Message
MessageConsumer consumer = session.createConsumer(queue);
consumer.setMessageListener(new MessageListener() {

@Override
public void onMessage(Message message) {
try {
System.out.println("Start to receive the message");
// Create a new Message Producer to send the reply message.
MessageProducer producer = session.createProducer(message
.getJMSReplyTo());
producer.send(session.createTextMessage("Hello"
+ ((TextMessage) message).getText()));

System.out.println("Consumer receive the message and reply sucessfully");
} catch (Exception e) {
e.printStackTrace();
}

}
});

// The receiver is used to receive the replied message
MessageConsumer consumer2 = session.createConsumer(replyQueue);
consumer2.setMessageListener(new MessageListener() {

@Override
public void onMessage(Message message) {
try {
System.out.println(((TextMessage)message).getText());
} catch (JMSException e) {
e.printStackTrace();
}

}
});
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值