Spring对JMS支持得非常好,使用起来也很方便;下面是使用Spring的方法。
准备工作:
想要运行Messaging客户端,需要几个包,请参见< http://labs.jboss.com/file-access/default/members/jbossmessaging/freezone/docs/userguide-1.4.0.SP1/html/installation.html>
1.配置JMS ConnectionFactory
<jee:jndi-lookup id="jmsConnectionFactory" jndi-name="ConnectionFactory">
<jee:environment>
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost:1099
</jee:environment>
</jee:jndi-lookup>
2.配置发送JMS的JmsTemplate
<bean id="jmsTemplate" lazy-init="true" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="jmsConnectionFactory" />
<property name="defaultDestinationName" value="A" />
</bean>
3.配置JMS的接收器
<bean id="messageListener" class="jms.receiver.SimpleMessageListener" />
该Class必须实现javax.jms.MessageListener接口
4.配置JMS ListenerContainer
<bean id="listenerContainerQueue" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="concurrentConsumers" value="1" />
<property name="connectionFactory" ref="jmsConnectionFactory" />
<property name="destinationName" value="A" />
<property name="messageListener" ref="messageListener" />
<property name="exceptionListener" ref="exceptionListener" />
</bean>
5.如果需要的话,配置JMS ExceptionListener
<bean id="exceptionListener" class="jms.receiver.SimpleExceptionListener" />
同理,该Class必须实现javax.jms.ExceptionListener接口
6.发送Jms消息
String strTest = "JmsTest";
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext_Sender.xml");
JmsTemplate template = (JmsTemplate) factory.getBean("jmsTemplate");
template.convertAndSend(strTest);
System.out.println(strTest);
7.接收Jms消息
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext_Receiver.xml");
只需要初始化配置文件就可以接收了