我想知道如何根据建议使用ActiveMQ进行测试的答案使用ActiveMQ来测试JMS Simulating JMS - jUnit
但是,我没有收到MessageConsumer所期望的消息。如果我用过它就会挂在那里。
这是我的代码
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Assert;
import org.junit.Test;
public class JmsTest {
@Test
public void test() throws Exception {
final ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"vm://localhost?broker.persistent=true");
final Queue queue;
final Connection connection = connectionFactory.createConnection();
final Session session = connection.createSession(true,
Session.AUTO_ACKNOWLEDGE);
{
queue = session.createQueue("test");
}
{
final MessageProducer producer = session.createProducer(queue);
final TextMessage message = session.createTextMessage("testing");
producer.send(message);
}
{
final MessageConsumer consumer = session.createConsumer(queue);
final TextMessage message = (TextMessage) consumer.receiveNoWait();
// "message" is null at this point
Assert.assertEquals("testing", message.getText());
}
}
}
答案 0 :(得分:2)
在收到消息之前,您需要调用connection.start(),否则不会向消费者分派任何消息。此外,您的代码不应该假设receiveNoWait将始终返回消息,因为消息可能需要花费一小段时间才能出列并路由到使用者,因此尝试在那里重试或使用调用的定时receive()可能是适当。
答案 1 :(得分:1)
谢谢蒂姆,我们几乎在同一时间找到了它,但我必须做一些其他修改,正如我在评论中指出的那样。简而言之,我必须确保“transactional”属性为“false”,并且Tim已经注意到我必须执行connection.start()调用。
@Test
public void test() throws Exception {
final ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"vm://localhost?broker.persistent=false");
final Connection connection = connectionFactory.createConnection();
connection.start();
final Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
final Queue queue = session.createTemporaryQueue();
{
final MessageProducer producer = session.createProducer(queue);
final TextMessage message = session.createTextMessage("testing");
producer.send(message);
}
{
final MessageConsumer consumer = session.createConsumer(queue);
final TextMessage message = (TextMessage) consumer.receiveNoWait();
Assert.assertNotNull(message);
Assert.assertEquals("testing", message.getText());
}
}
答案 2 :(得分:1)
使用主题看起来像这样:
final ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
final javax.jms.Connection connection = connectionFactory.createConnection();
connection.setClientID("12345");
connection.start();
final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Topic temporaryTopic = session.createTemporaryTopic();
final MessageConsumer consumer1 = session.createConsumer(temporaryTopic);
final MessageProducer producer = session.createProducer(temporaryTopic);
producer.send(session.createTextMessage("Testmessage"));
final TextMessage message = (TextMessage)consumer1.receiveNoWait();
Assert.assertNotNull(message);
Assert.assertEquals("testing", message.getText());