我正在尝试使用JMS和临时队列以典型的请求/响应(RPC)方式使用RabbitMQ。
我创建一个请求消息,将“回复队列”设置为一个新创建的临时队列,然后尝试回复此队列,然后尝试接收此队列的响应。我遇到的问题是该队列在我无法使用之前就消失了。
我尝试调试,似乎临时队列不是在请求阶段创建的,而是在响应阶段创建的,因此此队列的生存期与应答器连接(我在收到响应之前关闭)联系在一起,而不是请求者连接。我是在做错什么还是错误?
import static org.junit.Assert.assertEquals;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.junit.Test;
import com.rabbitmq.jms.admin.RMQConnectionFactory;
public class TmpQueueTest {
@Test
public void test() throws Exception
{
RMQConnectionFactory rmqConnectionFactory = new RMQConnectionFactory();
rmqConnectionFactory.setHost("127.0.0.1");
rmqConnectionFactory.setPort(5672);
try(Connection connection = rmqConnectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE))
{
connection.start();
{
Destination replyToQ = session.createTemporaryQueue();
Destination destinationQ = session.createQueue("dest");
MessageProducer producer = session.createProducer(destinationQ);
TextMessage message = session.createTextMessage("RTQ test");
message.setJMSReplyTo(replyToQ);
producer.send(message);
try(Connection connection2 = rmqConnectionFactory.createConnection();
Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE))
{
connection2.start();
MessageConsumer consumer = session2.createConsumer(destinationQ);
Message received = consumer.receive(1000);
assertEquals(replyToQ, received.getJMSReplyTo());
MessageProducer replierProducer = session2.createProducer(received.getJMSReplyTo());
replierProducer.send(received);
}
MessageConsumer responseConsumer = session.createConsumer(replyToQ);
TextMessage receivedResponse = (TextMessage) responseConsumer.receive(1000);
System.out.println("Message " + message);
System.out.println("Received message " + receivedResponse);
assertEquals(message.getText(), receivedResponse.getText());
}
}
}
}