我正在尝试运行一个非常基本的应用程序来学习 Spring JMS + ActiveMQ。我看到我的 Producer 创建了消息 (sysout),但我的 Consumer 中没有显示任何内容,也没有引发异常。我想我在这里遗漏了一些简单的东西;非常感谢任何帮助。
[已编辑,以下代码有效]
制片人:
@Component
public class JmsMessageProducer
{
@Autowired
private JmsTemplate template;
public void generateMessages() throws JMSException
{
template.send(new MessageCreator()
{
public Message createMessage(Session session) throws JMSException
{
System.out.println("sending..");
TextMessage message = session.createTextMessage("this is a Producer created message!");
return message;
}
});
}
}
消费者:
@Component
public class JmsMessageConsumer implements MessageListener {
@Override
public void onMessage(Message message) {
if (message instanceof TextMessage) {
TextMessage tm = (TextMessage) message;
try {
System.out.println("CONSUMER - received ["+tm.getText()+"]");
}
catch (Throwable th) {
th.printStackTrace();
}
}
}
}
生产者配置:
<context:component-scan base-package="mrpomario.springcore.jms"/> <!-- finds the JmsMessageProducer -->
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:8082"/>
</bean>
<bean id="pomarioQueue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="mrpomario.springcore.jms.queue"/>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="defaultDestination" ref="pomarioQueue"/>
</bean>
消费者配置:
<jms:listener-container>
<jms:listener ref="jmsMessageConsumer" method="onMessage" destination="mrpomario.springcore.jms.queue"/>
</jms:listener-container>
<bean id="pomarioQueue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="mrpomario.springcore.jms.queue"/>
</bean>
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:8082"/>
</bean>
<amq:broker id="broker" useJmx="false" persistent="false">
<amq:transportConnectors>
<amq:transportConnector uri="tcp://localhost:8082" />
</amq:transportConnectors>
</amq:broker>
测试用例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:mrpomario/springcore/jms/jms-config.xml")
public class JmsTest
{
@Autowired
JmsMessageProducer jmsMessageProducer;
@Test
public void test_Single_Queue_Producer_and_Consumer_Unidirectional() throws JMSException
{
try
{
jmsMessageProducer.generateMessages();
assertTrue(true);
}
catch (Throwable th)
{
System.out.println("\n\nJmsTest: remote invocation failed. Ensure the web server is running.\n\n");
}
}
}
我在 Java EE 容器 (mvn jetty:run) 中运行生产者,Spring MVC 应用程序也在该容器中运行。