springboot + activeMQ基本使用(springboot整合ActiveMQ)

一,Windows安装 ActiveMQ

1、下载地址:http://activemq.apache.org/download-archives.html ,本文用的是windows版的5.15.3版本,下载下来是压缩包。apache-activemq-5.15.3-bin.zip 

2、将压缩包解压一个到目录下,CMD进入到解压目录下的bin目录下,执行 activemq.bat start 启动。 如果能成功访问 http://localhost:8161/admin(用户名和密码默认为admin),则启动成功。

二,maven引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
 </dependency>
        <!-- 如果开启activeMQ的连接池,请引入pooled-jms,引入activemq-pool会报错。 -->
<dependency>
            <groupId>org.messaginghub</groupId>
            <artifactId>pooled-jms</artifactId>
 </dependency>

三,配置消息队列

@Configuration
public class SystemConfig {
    
    @Autowired
    private ConnectionFactory activeMQConnectionFactory
   
    //消息队列名称
    @Bean(name = "queue")
    public Queue queue2() {
        return new ActiveMQQueue("sysLog-send");
    }
    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerTopic() {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setPubSubDomain(true);
        bean.setConnectionFactory(activeMQConnectionFactory);
        return bean;
    }

    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerQueue() {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setPubSubDomain(true);
        bean.setConnectionFactory(activeMQConnectionFactory);
        return bean;
    }

}

四,application.yml引入activeMQ配置

spring:
    activemq:
        broker-url: tcp://127.0.0.1:61616
        pool:
          enabled: true
          max-connections: 100
        in-memory: true

五,发送端(生产者)

@RestController()
public class avtiveMQControllerTest {
    @Autowired
    private JmsMessagingTemplate jmsTemplate;

    @RequestMapping(value="/show/{name}", method = RequestMethod.GET)
    private void sendMessage(@PathVariable("name") String name){
        jmsTemplate.convertAndSend(destiationName, message);
        Map<String, Object> jmsNoticeMap = new HashMap<>(15);
        jmsNoticeMap.put("name", name);
        this.jmsTemplate.convertAndSend("sysLog-send", JSON.toJSONString(jmsNoticeMap, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero));
    }
}

六,接收端(消费者)

@Component
@Slf4j
public class activeMQJms {
    
    @JmsListener(destination = "sysLog-send")
    public void receiveScanResult2(String msg) {
        log.info("收到消息:" + msg);
    }
}


版权声明:本文为xiangge52原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。