
ActiveMQ是Apache发布的一款功能强大的消息中间件,它基于JMS 1.1 和 J2EE 1.4规范,目前使用十分广泛。
ActiveMQ的主要特点如下:
本节介绍ActiveMQ在Linux系统上的安装与运行:
tar -zxvf apache-activemq-5.15.5-bin.tar.gzcd apache-activemq-5.15.5
sh bin/activemq startnetstat -nltp | grep 61616
tcp        0      0 :::61616                    :::*                        LISTEN      10337/javash bin/activemq stopSpringBoot提供了对JMS的支持。因为ActiveMQ实现了JMS规范,因此可以使用SpringBoot快速地整合ActiveMQ。下面介绍具体步骤:
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>#ActiveMQ配置
spring:
 activemq:
   broker-url: 'tcp://localhost:61616'   #配置Broker URL,默认为tcp://localhost:61616
   in-memory: true
   pool:
     enabled:  false/**
* @Auther: ZhangShenao
* @Date: 2018/8/29 07:48
* @Description: ActiveMQ消息生产者
*/
@Service
public class MessageProducer {
   //也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装
   @Autowired
   private JmsMessagingTemplate jmsMessagingTemplate;
   /**
    * 发送消息
    * @param destination 要发送到的队列
    * @param payload 待发送的消息
    */
   public void sendMessage(Destination destination,String payload){
       jmsMessagingTemplate.convertAndSend(destination,payload);
   }
}/**
* @Auther: ZhangShenao
* @Date: 2018/8/29 08:24
* @Description: ActiveMQ 消息消费者
*/
@Service
public class MessageConsumer {
   //使用JmsListener配置消费者监听指定的队列,其中message是接收到的消息
   @JmsListener(destination = "my-queue")
   public void receiveMessage(String message){
       System.err.println("接收到了消息: " + message);
   }
}/**
* @Auther: ZhangShenao
* @Date: 2018/8/29 08:28
* @Description: ActiveMQ 测试
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestActiveMQ {
   @Autowired
   private MessageProducer producer;
   @Test
   public void testSendMessage(){
       Destination destination = new ActiveMQQueue("my-queue");
       for (int i = 1;i <= 100;i++){
           producer.sendMessage(destination,"message-" + i);
       }
   }
}接收到了消息: message-1
接收到了消息: message-2
接收到了消息: message-3
接收到了消息: message-4
接收到了消息: message-5
接收到了消息: message-6
接收到了消息: message-7
接收到了消息: message-8
接收到了消息: message-9
接收到了消息: message-10
接收到了消息: message-11
接收到了消息: message-12
...