转:spring boot + ActiveMQ 实现消息服务

首先,我在github上找到了一个不错的demo,这里放给大家一起看下:

https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-activemq

 

确实可以实现功能,但是当我在8161默认的admin端口进行queue查询时,发现并没有我们的github-queue,虽然不太清楚具体的原因,但是解决方式倒是找到了,下面贴一下自己的实现:

pox.xml:

Java代码   收藏代码
  1. <!-- ActiveMQ -->  
  2.         <dependency>  
  3.             <groupId>org.springframework</groupId>  
  4.             <artifactId>spring-jms</artifactId>  
  5.         </dependency>  
  6.         <dependency>  
  7.             <groupId>org.apache.activemq</groupId>  
  8.             <artifactId>activemq-all</artifactId>  
  9.             <version>5.13.2</version>  
  10.         </dependency>  

application.properties:

Java代码   收藏代码
  1. spring.activemq.in-memory=true  
  2. spring.activemq.pooled=false  

 

 

接下来就是jms的配置了,首先是ActiveMQ4Config文件:

Java代码   收藏代码
  1. @EnableJms  
  2. @Configuration  
  3. public class ActiveMQ4Config {  
  4.   
  5.     @Bean  
  6.     public Queue queue() {  
  7.         return new ActiveMQQueue("github-queue");  
  8.     }  
  9.   
  10.     @Bean  
  11.     public ActiveMQConnectionFactory activeMQConnectionFactory (){  
  12.         ActiveMQConnectionFactory activeMQConnectionFactory =  
  13.                 new ActiveMQConnectionFactory(  
  14.                         ActiveMQConnectionFactory.DEFAULT_USER,  
  15.                         ActiveMQConnectionFactory.DEFAULT_PASSWORD,  
  16. //                        "tcp://192.168.0.100:61616");  
  17.                         ActiveMQConnectionFactory.DEFAULT_BROKER_URL);  
  18.         return activeMQConnectionFactory;  
  19.     }  
  20.   
  21. }  

注释掉的那行,可以用来指定activemq的broker地址。

 

接下来的Producer和Consumer与github上一样:

Java代码   收藏代码
  1. @Component  
  2. public class Producer implements CommandLineRunner{  
  3.   
  4.     @Autowired  
  5.     private JmsMessagingTemplate jmsMessagingTemplate;  
  6.   
  7.     @Autowired  
  8.     private Queue queue;  
  9.   
  10.     @Override  
  11.     public void run(String... args) throws Exception {  
  12.         send("this message is send on begining!");  
  13.         System.out.println("Message was sent to the Queue");  
  14.     }  
  15.   
  16.     public void send(String msg) {  
  17.         this.jmsMessagingTemplate.convertAndSend(this.queue, msg);  
  18.     }  
  19.   
  20. }  
Java代码   收藏代码
  1. @Component  
  2. public class Consumer {  
  3.   
  4.     @JmsListener(destination = "github-queue")  
  5.     public void receiveQueue(String text) {  
  6.         System.out.println(text);  
  7.     }  
  8.   
  9. }  

 

这样一来就完成了配置,而且在8161默认admin进行查询时,是能够查询到我们的github-queue这个队列的。

具体的测试,可以自己进行,这里不再贴测试用例了。

猜你喜欢

转载自sunbin.iteye.com/blog/2285883