ActiveMQ与Spring的例子

publicclassActivemqTestextendsTestCase{

@Test

publicvoidtestJmsTemplateSend(){

ApplicationContextctx=newClassPathXmlApplicationContext(

"/applicationContext-jms.xml");

JmsTemplatetemplate=(JmsTemplate)ctx.getBean("jmsTemplate");

Destinationdestination=(Destination)ctx.getBean("destination");

template.send(destination,newMessageCreator(){

publicMessagecreateMessage(Sessionsession)throwsJMSException{

returnsession

.createTextMessage("发送消息:HelloActiveMQTextMessage!");

}

});

System.out.println("成功发送了一条JMS消息");

}

@Test

publicvoidtestJmsTemplateReceive()throwsJMSException{

ApplicationContextctx=newClassPathXmlApplicationContext(

"/applicationContext-jms.xml");

JmsTemplatetemplate=(JmsTemplate)ctx.getBean("jmsTemplate");

Destinationdestination=(Destination)ctx.getBean("destination");

while(true){

TextMessagetxtmsg=(TextMessage)template.receive(destination);

if(null!=txtmsg)

System.out.println("收到消息内容为:"+txtmsg.getText());

else

break;

}

}

}

applicationContext-jms.xml文件:

Java代码收藏代码

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<!--配置JMS连接工厂-->

<beanid="connectionFactory"class="org.apache.activemq.spring.ActiveMQConnectionFactory">

<propertyname="brokerURL"value="tcp://localhost:61616"/>

</bean>

<!--配置JMS模版-->

<beanid="jmsTemplate"class="org.springframework.jms.core.JmsTemplate">

<propertyname="connectionFactory"ref="connectionFactory"/>

</bean>

<!--发送消息的目的地(一个队列)-->

<beanid="destination"class="org.apache.activemq.command.ActiveMQQueue">

<!--SettheQueueName-->

<constructor-argindex="0"value="HelloWorldQueue"/>

</bean>

</beans>

特殊的jar

Java代码收藏代码

activemq-core-5.2.0.jar

geronimo-j2ee-management_1.0_spec-1.0.jar

spring-jms-2.5.5.jar

xbean-spring-3.4.jar

相关推荐