第一: 在applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>tcp://192.168.3.48:61616</value>
</property>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref bean="connectionFactory"/>
</property>
</bean>
<bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0">
<value>HelloWorldQueue</value>
</constructor-arg>
</bean>
</beans>
2.写发送方
package ch13.JMS;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
public class HelloWorldSender
{
public static void main(String args[]) throws Exception
{
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "ch13/JMS/applicationContext.xml" });
JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");
Destination destination = (Destination) context.getBean("destination");
jmsTemplate.send
(
destination, new MessageCreator()
{
public Message createMessage(Session session) throws JMSException
{
return session.createTextMessage("大家好这个是测试!");
}
}
);
}
}
3.写接收方
package ch13.JMS;
import javax.jms.Destination;
import javax.jms.TextMessage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
public class HelloWorldReciver
{
public static void main(String args[]) throws Exception
{
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "ch13/JMS/applicationContext.xml" });
JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");
Destination destination = (Destination) context.getBean("destination");
System.out.println("will wait:" + jmsTemplate.getReceiveTimeout()+ " seconds for message");
TextMessage msg = (TextMessage) jmsTemplate.receive(destination);
System.out.println("reviced msg is:" + msg.getText());
}
}
4.启动activemq中bin 下的activemq.bat
5.先运行 HelloWorldSender
6.再运行 HelloWorld
7.结果:
will wait:-1 seconds for message
reviced msg is:大家好 这个是测试!