ActiveMQ整合Spring——发送消息

需要的jar包:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.3.RELEASE</version> </dependency>
<dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-jms</artifactId>     <version>4.1.3.RELEASE</version>    </dependency>
<dependency>     <groupId>org.apache.activemq</groupId>     <artifactId>activemq-all</artifactId>     <version>5.11.2</version> </dependency>

新建spring-activemq.xml,配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://code.alibabatech.com/schema/dubbo 
     http://code.alibabatech.com/schema/dubbo/dubbo.xsd
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->
	<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
		<property name="brokerURL" value="tcp://192.168.25.134:61616" />
	</bean>
	<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
	<bean id="connectionFactory"
		class="org.springframework.jms.connection.SingleConnectionFactory">
		<!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
		<property name="targetConnectionFactory" ref="targetConnectionFactory" />
	</bean>
	<!-- 配置生产者 -->
	<!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
	<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
		<!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
		<property name="connectionFactory" ref="connectionFactory" />
	</bean>
	<!--这个是队列目的地,点对点的 -->
	<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
		<constructor-arg>
			<value>spring-queue</value>
		</constructor-arg>
	</bean>
	<!--这个是主题目的地,一对多的 -->
	<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
		<constructor-arg value="topic" />
	</bean>


</beans>

在java代码中的具体应用:

        @Autowired
	private JmsTemplate jmsTemplate;
	@Resource
	private Destination topicDestination;//使用命名注入,使用topic消息形式


       @Override
	public E3Result saveItemService(TbItem tbItem, String desc) {
		//发送消息
		final long itemId = 111;
		jmsTemplate.send(topicDestination, new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				// TODO Auto-generated method stub
				TextMessage createTextMessage = session.createTextMessage();
				System.out.println(itemId);
				createTextMessage.setText(itemId + "");
				return createTextMessage;
			}
		});
	}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页