Spring集成ActiveMQ配置

1.       集成环境

Spring采用2.5.6版本,ActiveMQ使用的是5.4.2,从apache站点可以下载。本文是将Spring集成ActiveMQ来发送和接收JMS消息。

2.       集成步骤

将下载的ActiveMQ解压缩后文件夹如下

 activemq-all-5.4.2.jar是activemq的所有的类jar包。lib下面是模块分解后的jar包。将lib下面的

Java代码 复制代码  收藏代码
  1. /lib/activation-1.1.jar   
  2. /lib/activemq-camel-5.4.2.jar   
  3. /lib/activemq-console-5.4.2.jar   
  4. /lib/activemq-core-5.4.2.jar   
  5. /lib/activemq-jaas-5.4.2.jar   
  6. /lib/activemq-pool-5.4.2.jar   
  7. /lib/activemq-protobuf-1.1.jar   
  8. /lib/activemq-spring-5.4.2.jar   
  9. /lib/activemq-web-5.4.2.jar  
/lib/activation-1.1.jar
/lib/activemq-camel-5.4.2.jar
/lib/activemq-console-5.4.2.jar
/lib/activemq-core-5.4.2.jar
/lib/activemq-jaas-5.4.2.jar
/lib/activemq-pool-5.4.2.jar
/lib/activemq-protobuf-1.1.jar
/lib/activemq-spring-5.4.2.jar
/lib/activemq-web-5.4.2.jar

文件全部拷贝到项目中。

而Spring项目所需要的jar包如下 

Java代码 复制代码  收藏代码
  1. /lib/spring-beans-2.5.6.jar   
  2. /lib/spring-context-2.5.6.jar   
  3. /lib/spring-context-support-2.5.6.jar   
  4. /lib/spring-core-2.5.6.jar   
  5. /lib/spring-jms-2.5.6.jar   
  6. /lib/spring-tx.jar  
/lib/spring-beans-2.5.6.jar
/lib/spring-context-2.5.6.jar
/lib/spring-context-support-2.5.6.jar
/lib/spring-core-2.5.6.jar
/lib/spring-jms-2.5.6.jar
/lib/spring-tx.jar

当然还需要一些其他的jar文件

Java代码 复制代码  收藏代码
  1. /lib/geronimo-j2ee-management_1.1_spec-1.0.1.jar   
  2. /lib/jms-1.1.jar   
  3. /lib/log4j-1.2.15.jar   
  4. /lib/slf4j-api-1.6.1.jar   
  5. /lib/slf4j-nop-1.6.1.jar  
/lib/geronimo-j2ee-management_1.1_spec-1.0.1.jar
/lib/jms-1.1.jar
/lib/log4j-1.2.15.jar
/lib/slf4j-api-1.6.1.jar
/lib/slf4j-nop-1.6.1.jar

项目的依赖jar都准备好后就可以写配置文件了。

 Spring配置文件

配置文件内容如下

Java代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans    
  5.         http://www.springframework.org/schema/beans/spring-beans-2.5.xsd    
  6.         http://www.springframework.org/schema/context    
  7.         http://www.springframework.org/schema/context/spring-context-2.5.xsd"   
  8.     default-autowire="byName">   
  9.   
  10.   
  11.     <!-- 配置connectionFactory -->   
  12.     <bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory"  
  13.         destroy-method="stop">   
  14.         <property name="connectionFactory">   
  15.             <bean class="org.apache.activemq.ActiveMQConnectionFactory">   
  16.                 <property name="brokerURL">   
  17.                     <value>tcp://127.0.0.1:61616</value>   
  18.                 </property>   
  19.             </bean>   
  20.         </property>   
  21.         <property name="maxConnections" value="100"></property>   
  22.     </bean>   
  23.   
  24.     <!-- Spring JMS Template -->   
  25.     <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">   
  26.         <property name="connectionFactory">   
  27.             <ref local="jmsFactory" />   
  28.         </property>   
  29.         <property name="defaultDestinationName" value="subject" />   
  30.         <!-- 区别它采用的模式为false是p2p为true是订阅 -->   
  31.         <property name="pubSubDomain" value="true" />   
  32.     </bean>   
  33.   
  34.     <!-- 发送消息的目的地(一个队列) -->   
  35.     <bean id="destination" class="org.apache.activemq.command.ActiveMQTopic">   
  36.         <!-- 设置消息队列的名字 -->   
  37.         <constructor-arg index="0" value="subject" />   
  38.     </bean>   
  39.   
  40.     <!-- 消息监听     -->   
  41.     <bean id="listenerContainer"  
  42.         class="org.springframework.jms.listener.DefaultMessageListenerContainer">   
  43.         <property name="concurrentConsumers" value="10" />   
  44.         <property name="connectionFactory" ref="jmsFactory" />   
  45.         <property name="destinationName" value="subject" />   
  46.         <property name="messageListener" ref="messageReceiver" />   
  47.         <property name="pubSubNoLocal" value="false"></property>   
  48.     </bean>   
  49.   
  50.     <bean id="messageReceiver"  
  51.         class="com.liuyan.jms.consumer.ProxyJMSConsumer">   
  52.         <property name="jmsTemplate" ref="jmsTemplate"></property>   
  53.     </bean>   
  54. </beans>  
<?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: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"
	default-autowire="byName">


	<!-- 配置connectionFactory -->
	<bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
		destroy-method="stop">
		<property name="connectionFactory">
			<bean class="org.apache.activemq.ActiveMQConnectionFactory">
				<property name="brokerURL">
					<value>tcp://127.0.0.1:61616</value>
				</property>
			</bean>
		</property>
		<property name="maxConnections" value="100"></property>
	</bean>

	<!-- Spring JMS Template -->
	<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
		<property name="connectionFactory">
			<ref local="jmsFactory" />
		</property>
		<property name="defaultDestinationName" value="subject" />
		<!-- 区别它采用的模式为false是p2p为true是订阅 -->
		<property name="pubSubDomain" value="true" />
	</bean>

	<!-- 发送消息的目的地(一个队列) -->
	<bean id="destination" class="org.apache.activemq.command.ActiveMQTopic">
		<!-- 设置消息队列的名字 -->
		<constructor-arg index="0" value="subject" />
	</bean>

	<!-- 消息监听     -->
	<bean id="listenerContainer"
		class="org.springframework.jms.listener.DefaultMessageListenerContainer">
		<property name="concurrentConsumers" value="10" />
		<property name="connectionFactory" ref="jmsFactory" />
		<property name="destinationName" value="subject" />
		<property name="messageListener" ref="messageReceiver" />
		<property name="pubSubNoLocal" value="false"></property>
	</bean>

	<bean id="messageReceiver"
		class="com.liuyan.jms.consumer.ProxyJMSConsumer">
		<property name="jmsTemplate" ref="jmsTemplate"></property>
	</bean>
</beans>

编写代码

消息发送者:这里面消息生产者并没有在Spring配置文件中进行配置,这里仅仅使用了Spring中的JMS模板和消息目的而已。 

Java代码 复制代码  收藏代码
  1. public class HelloSender {   
  2.   
  3.     /**  
  4.      * @param args  
  5.      */  
  6.     public static void main(String[] args) {   
  7.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(   
  8.                 new String[] { "classpath:/spring/applicationContext-jms.xml" });   
  9.            
  10.         JmsTemplate template = (JmsTemplate) applicationContext   
  11.                 .getBean("jmsTemplate");   
  12.            
  13.         Destination destination = (Destination) applicationContext   
  14.                 .getBean("destination");   
  15.   
  16.         template.send(destination, new MessageCreator() {   
  17.             public Message createMessage(Session session) throws JMSException {   
  18.                 return session   
  19.                         .createTextMessage("发送消息:Hello ActiveMQ Text Message!");   
  20.             }   
  21.         });   
  22.         System.out.println("成功发送了一条JMS消息");   
  23.   
  24.     }   
  25.   
  26. }  
public class HelloSender {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				new String[] { "classpath:/spring/applicationContext-jms.xml" });
		
		JmsTemplate template = (JmsTemplate) applicationContext
				.getBean("jmsTemplate");
		
		Destination destination = (Destination) applicationContext
				.getBean("destination");

		template.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session
						.createTextMessage("发送消息:Hello ActiveMQ Text Message!");
			}
		});
		System.out.println("成功发送了一条JMS消息");

	}

}

消息接收

Java代码 复制代码  收藏代码
  1. /**  
  2.  * JMS消费者  
  3.  *   
  4.  *   
  5.  * <p>  
  6.  * 消息题的内容定义  
  7.  * <p>  
  8.  * 消息对象 接收消息对象后: 接收到的消息体* <p>   
  9.  */  
  10. public class ProxyJMSConsumer {   
  11.   
  12.     public ProxyJMSConsumer() {   
  13.   
  14.     }   
  15.   
  16.     private JmsTemplate jmsTemplate;   
  17.   
  18.     public JmsTemplate getJmsTemplate() {   
  19.         return jmsTemplate;   
  20.     }   
  21.   
  22.     public void setJmsTemplate(JmsTemplate jmsTemplate) {   
  23.         this.jmsTemplate = jmsTemplate;   
  24.     }   
  25.   
  26.     /**  
  27.      * 监听到消息目的有消息后自动调用onMessage(Message message)方法  
  28.      */  
  29.     public void recive() {   
  30.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(   
  31.                 new String[] { "classpath:/spring/applicationContext-jms.xml" });   
  32.   
  33.         Destination destination = (Destination) applicationContext   
  34.                 .getBean("destination");   
  35.   
  36.         while (true) {   
  37.   
  38.             try {   
  39.                 TextMessage txtmsg = (TextMessage) jmsTemplate   
  40.                         .receive(destination);   
  41.                 if (null != txtmsg) {   
  42.                     System.out.println("[DB Proxy] " + txtmsg);   
  43.                     System.out.println("[DB Proxy] 收到消息内容为: "  
  44.                             + txtmsg.getText());   
  45.                 } else  
  46.                     break;   
  47.             } catch (Exception e) {   
  48.                 e.printStackTrace();   
  49.             }   
  50.   
  51.         }   
  52.     }   
  53.   
  54. }  
/**
 * JMS消费者
 * 
 * 
 * <p>
 * 消息题的内容定义
 * <p>
 * 消息对象 接收消息对象后: 接收到的消息体* <p> 
 */
public class ProxyJMSConsumer {

	public ProxyJMSConsumer() {

	}

	private JmsTemplate jmsTemplate;

	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	/**
	 * 监听到消息目的有消息后自动调用onMessage(Message message)方法
	 */
	public void recive() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				new String[] { "classpath:/spring/applicationContext-jms.xml" });

		Destination destination = (Destination) applicationContext
				.getBean("destination");

		while (true) {

			try {
				TextMessage txtmsg = (TextMessage) jmsTemplate
						.receive(destination);
				if (null != txtmsg) {
					System.out.println("[DB Proxy] " + txtmsg);
					System.out.println("[DB Proxy] 收到消息内容为: "
							+ txtmsg.getText());
				} else
					break;
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

}

这里边也是并不是直接使用Spring来初始化建立消息消费者实例,而是在此消费者注入了JMS模板而已。

写一个main入口,初始化消息消费者  

Java代码 复制代码  收藏代码
  1. public class JMSTest {   
  2.   
  3.     /**  
  4.      * @param args  
  5.      */  
  6.     public static void main(String[] args) {   
  7.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(   
  8.                 new String[] { "classpath:/spring/applicationContext-jms.xml" });   
  9.            
  10.         ProxyJMSConsumer proxyJMSConsumer = (ProxyJMSConsumer) applicationContext   
  11.                 .getBean("messageReceiver");   
  12.            
  13.         System.out.println("初始化消息消费者");   
  14.     }   
  15.   
  16. }  
public class JMSTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				new String[] { "classpath:/spring/applicationContext-jms.xml" });
		
		ProxyJMSConsumer proxyJMSConsumer = (ProxyJMSConsumer) applicationContext
				.getBean("messageReceiver");
		
		System.out.println("初始化消息消费者");
	}

}

使用的时候先开启ActiveMQ服务,默认是占用了61616端口。之后开启测试程序,开启2个消息消费者监听。之后再运行消息生产者的代码后,消息就可以被消息消费者接收到了。 

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: Spring Boot 集成 ActiveMQ 很简单,只需要在项目的 pom.xml 文件中添加 ActiveMQ 的依赖,然后在配置文件 application.properties 中配置 ActiveMQ 的地址即可。具体步骤如下: 1. 在 pom.xml 文件中添加 ActiveMQ 的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> ``` 2. 在 application.properties 文件中配置 ActiveMQ 的地址,例如: ``` spring.activemq.broker-url=tcp://localhost:61616 ``` 3. 在启动类中添加 @EnableJms 注解,表示启用 JMS。 4. 创建一个 JmsTemplate 对象来发送和接收消息。 完成以上步骤即可在 Spring Boot 中使用 ActiveMQ。 ### 回答2: Spring Boot是Spring Framework的一个用于简化Spring应用程序开发和部署的框架。它提供了一种简单的方式来开发、构建和运行Spring应用程序,同时也能方便地集成其他框架和技术。 ActiveMQ是一个流行的开源消息代理,它支持多种协议和编程语言,包括Java、C#、C++、Python等。它提供了可靠的消息传递机制,可以用于构建分布式系统和异步消息处理应用。 Spring Boot提供了对ActiveMQ集成支持,可以通过在pom.xml文件中添加相关依赖和配置,实现快速集成和使用ActiveMQ。 下面是详细的步骤: 1. 在pom.xml文件中添加ActiveMQ的依赖: ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> </dependencies> ``` 2. 在application.properties文件中添加ActiveMQ配置: ``` spring.activemq.broker-url=tcp://localhost:61616 spring.activemq.user=admin spring.activemq.password=admin ``` 其中broker-url是ActiveMQ的连接地址,user和password是登录信息。 3. 在代码中使用JmsTemplate发送和接收消息: ``` @Service public class MessageService { @Autowired private JmsTemplate jmsTemplate; public void sendMessage(String message) { jmsTemplate.send("test.queue", new MessageCreator() { public Message createMessage(Session session) throws JMSException { return session.createTextMessage(message); } }); } @JmsListener(destination = "test.queue") public void receiveMessage(String message) { System.out.println("Received message: " + message); } } ``` 上面的代码定义了一个MessageService类,里面包含了一个sendMesssge方法和一个receiveMessage方法。sendMessage方法将消息发送到名为“test.queue”的队列中,而receiveMessage方法则监听该队列并接收消息。 在使用JmsTemplate发送消息时,需要提供消息的目的地和消息内容。这里使用createTextMessage方法创建一个文本消息,并将其发送到指定的队列中。 在使用@JmsListener注解接收消息时,需要指定监听的队列名称和接收消息的方法。接收到消息后,将会调用该方法并输出消息内容。 4. 运行应用程序并测试消息发送和接收功能。 启动应用程序后,调用MessageService的sendMessage方法即可发送消息到ActiveMQ,同时在控制台输出了接收到的消息。这样,就成功地实现了Spring Boot和ActiveMQ集成。 总之,通过以上步骤,我们可以很容易地将Spring Boot和ActiveMQ进行集成,在开发分布式系统和消息处理应用时,能够方便地使用ActiveMQ提供的可靠消息传递机制。 ### 回答3: Spring Boot是一种基于Spring框架的快速开发框架,它提供了很多便捷快捷的特性。ActiveMQ则是一种高性能、开源的消息传递中间件。Spring Boot和ActiveMQ的结合,能够搭建一个可插拔、可扩展、可重复利用的消息解决方案。下面将介绍如何在Spring Boot中集成ActiveMQ。 1、引入所需依赖 首先需要在项目中引入ActiveMQ相关的依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> 2、配置ActiveMQ 在application.properties文件中配置ActiveMQ,如下所示: #ActiveMQ configuration spring.activemq.broker-url=tcp://localhost:61616 spring.activemq.user=admin spring.activemq.password=admin spring.jms.template.default-destination=test-queue spring.jms.listener.auto-startup=true 其中,spring.activemq.broker-url指定了ActiveMQ服务器的地址;spring.activemq.user和spring.activemq.password是登录ActiveMQ服务器的用户名和密码;spring.jms.template.default-destination设置了默认的目的地队列;spring.jms.listener.auto-startup设置消息监听器的自动启动。 3、编写消息生产者代码 @Inject private JmsMessagingTemplate jmsMessagingTemplate; public void produceMessage(String message) { jmsMessagingTemplate.convertAndSend("test-queue", message); } 首先在类中注入JmsMessagingTemplate,它是Spring Boot提供的用于发送消息的工具类。然后编写produceMessage()方法,将消息发送到目的地队列test-queue中。 4、编写消息消费者代码 @JmsListener(destination="test-queue") public void receiveMessage(String message) { System.out.println("Received message: " + message); } 使用@JmsListener注解,在方法上指定监听的目的地队列为test-queue。当有消息到达test-queue时,就会自动调用receiveMessage()方法,进行消息处理。 通过上述步骤,就可以在Spring Boot中集成ActiveMQ,实现消息生产者和消息消费者的功能。当然,还可以通过其他方式来实现集成,例如使用ConnectionFactory或者JmsTemplate等Spring集成方式。这样就能够应用在更多的项目中,提高应用的可靠性和可扩展性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值