项目环境
JDK
ActiveMQ
所用的包都是ActiveMQ自带的引用的包如下图
package stujmspptxt;
import orgntextApplicationContext;
import orgntextsupportClassPathXmlApplicationContext;
import orgsprreJmsTemplate;
import orgsprreMessageCreator;
import javaxjmsDestination;
import javaxjmsJMSException;
import javaxjmsMessage;
import javaxjmsSession;
/**
* 消息发送者
*
* @author leizhimin ::
*/
public class MySender {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(/applicationContextxml);
JmsTemplate template = (JmsTemplate) ctxgetBean(jmsTemplate);
Destination destination = (Destination) ctxgetBean(destination);
templatesend(destination new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return sessioncreateTextMessage(发送消息Hello ActiveMQ Text Message!);
}
});
Systemoutprintln(成功发送了一条JMS消息);
}
}
package stujmspptxt;
import orgntextApplicationContext;
import orgntextsupportClassPathXmlApplicationContext;
import orgsprreJmsTemplate;
import javaxjmsDestination;
import javaxjmsJMSException;
import javaxjmsTextMessage;
/**
* 消息接收者
*
* @author leizhimin ::
*/
public class MyReceiver {
public static void main(String[] args) throws JMSException {
ApplicationContext ctx = new ClassPathXmlApplicationContext(/applicationContextxml);
JmsTemplate template = (JmsTemplate) ctxgetBean(jmsTemplate);
Destination destination = (Destination) ctxgetBean(destination);
while (true) {
TextMessage txtmsg = (TextMessage) templatereceive(destination);
if (null != txtmsg)
Systemoutprintln(收到消息内容为: + txtmsggetText());
else
break;
}
}
}
<?xml version= encoding=UTF?>
<beans xmlns= xmlns:xsi=instance
xmlns:context=
xsi:schemaLocation=
beansxsd
contextxsd>
<! 配置JMS连接工厂 >
<bean id=connectionFactory class=orgapacheactivemqspringActiveMQConnectionFactory>
<property name=brokerURL value=tcp://localhost:/>
</bean>
<! 配置JMS模版 >
<bean id=jmsTemplate class=orgsprreJmsTemplate>
<property name=connectionFactory ref=connectionFactory/>
</bean>
<! 发送消息的目的地(一个队列) >
<bean id=destination class=orgmandActiveMQQueue>
<! 设置消息队列的名字 >
<constructorarg index= value=HelloWorldQueue/>
</bean>
</beans>
运行发送端三次
成功发送了一条JMS消息
Process finished with exit code
然后再运行接收端一次
收到消息内容为: 发送消息Hello ActiveMQ Text Message!
收到消息内容为: 发送消息Hello ActiveMQ Text Message!
收到消息内容为: 发送消息Hello ActiveMQ Text Message!
继续测试发现接收端接收一条消息后不退出程序而是继续等待一旦有消息发送过来就获取到然后输出!
发一张图看看