spring boot 集成ActiveMQ

spring boot 集成ActiveMQ

昨天刚调通了kafka,工作原因 大多从事传统项目,实战比较少,今天学习一下ActiveMQ。 构建spring-boot工程请参照其他

  • ActiveMQ安装
    1.官方下载地址 http://activemq.apache.org/download.html
    2.apache-activemq-5.15.3\bin\win64\activeMQ.bat
    3.浏览器输入http://127.0.0.1:8161 官方默认账户密码 admin/admin
  • maven依赖
     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
     </dependency>
     <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-pool</artifactId>
    </dependency>
  • properties配置
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false
##如果此处设置为true,需要加如下的依赖包,否则会自动配置失败,报JmsMessagingTemplate注入失败
  • 生产者
package com.chinasofti.mq;
  
import javax.jms.Destination;  
  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.jms.core.JmsMessagingTemplate;  
import org.springframework.stereotype.Service;  
  
@Service("producer")  
public class Producer {  
    @Autowired // 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装  
    private JmsMessagingTemplate jmsTemplate;  
    // 发送消息,destination是发送到的队列,message是待发送的消息  
    public void sendMessage(Destination destination, final String message){  
        jmsTemplate.convertAndSend(destination, message);  
    }  
} 
  • 消费者
package com.chinasofti.mq;
  
import org.springframework.jms.annotation.JmsListener;  
import org.springframework.stereotype.Component;  
  
@Component  
public class Consumer {  
        // 使用JmsListener配置消费者监听的队列,其中text是接收到的消息  
    @JmsListener(destination = "mytest.queue")  
    public void receiveQueue(String text) {  
        System.out.println("Consumer收到的报文为:"+text);  
    }  
}  
  • Junit测试部分代码
   @Autowired
    private Producer producer;
    @Test
    public void contextLoads() throws InterruptedException {
        Destination destination = new ActiveMQQueue("mytest.queue");

        for(int i=0; i<100; i++){
            producer.sendMessage(destination, "一个Mq消息");
        }
    }
  • 执行结果
    这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值