springBoot整合ActiveMQ

本文介绍了如何将SpringBoot应用与ActiveMQ整合,包括下载ActiveMQ、导入依赖、配置文件设置、创建ActiveMQConfig、MessageProducer和MessageConsumer,以及使用监听模式。还提供了测试类ActiveMQTest和源码地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

操作之前先要去官网下载activeMQ。略过~~

1、导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-pool</artifactId>
        </dependency>

2、在配置文件中添加activeMQ相关配置

#activeMQ
spring.activemq.broker-url=tcp://127.0.0.1:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.pool.enabled=true
spring.activemq.pool.max-connections=50
spring.activemq.pool.idle-timeout=30000

3、创建ActiveMQConfig用于托管JmsTemplate,添加topic队列模式以及消息重发机制

package com.example.shiroredis.config;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.RedeliveryPolicy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.ConnectionFactory;

@Configuration
public class ActiveMQConfig {
    @Value("${spring.activemq.broker-url}")
    private String url;
    @Value("${spring.activemq.user}")
    private String name;
    @Value("${spring.activemq.password}")
    private String pwd;

    @Bean
    public ConnectionFactory connectionFactory(){
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        connectionFactory.setBrokerURL(url);
        connectionFactory.setUserName(name);
        connectionFactory.setPassword(pwd);
        //设置重发机制
        connectionFactory.setRedeliveryPolicy(activeMQRedeliveryPolicy());
        return connectionFactory;
    }
    @Bean
    public JmsTemplate genJmsTemplate(){
        JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory());
        return jmsTemplate;

    }
    @Bean
    public JmsMessagingTemplate jmsMessageTemplate() {
        return new JmsMessagingTemplate(connectionFactory());
    }

    @Bean
    public DefaultJmsListenerContainerFactory jmsTopicListenerContainerFactory() {

        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();

        factory.setConnectionFactory(connectionFactory());
        //true为topic,false为queue
        factory.setPubSubDomain(true);

        factory.setRecoveryInterval(1000L);
        factory.setConcurrency("1");
        return factory;
    }
    @Bean
    public RedeliveryPolicy activeMQRedeliveryPolicy(){
        RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
        //是否在每次尝试重新发送失败后,增长这个等待时间
        redeliveryPolicy.setUseExponentialBackOff(true);
        //重发次数,默认为6次   这里设置为1次
        redeliveryPolicy.setMaximumRedeliveries(1);
        //重发时间间隔,默认为1秒
        redeliveryPolicy.setInitialRedeliveryDelay(1000);
        //第一次失败后重新发送之前等待500毫秒,第二次失败再等待500 * 2毫秒,这里的2就是value
        redeliveryPolicy.setBackOffMultiplier(2);
        //最大传送延迟,只在useExponentialBackOff为true时有效(V5.5),假设首次重连间隔为10ms,倍数为2,
        // 那么第二次重连时间间隔为 20ms,第三次重连时间间隔为40ms,当重连时间间隔大的最大重连时间间隔时,以后每次重连时间间隔都为最大重连时间间隔。
        redeliveryPolicy.setMaximumRedeliveryDelay(1000);
        return redeliveryPolicy;
    }

}

4、创建消息生产者MessageProduce

package com.example.shiroredis.activemq;


import javax.jms.Destination;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;


@Service("messageProduce")
public class MessageProduce {

    @Autowired
    private JmsTemplate jmsTemplate;

    /**
     * 发送消息
     *
     * @param destination
     *            发送到的队列
     * @param message
     *            待发送的消息
     */
    public void convertAndSend(Destination destination, final String message) {
        jmsTemplate.convertAndSend(destination, message);
    }

}

5、创建消息消费者MessageConsumeNtwo 采用的是监听的模式

package com.example.shiroredis.activemq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
public class MessageConsumeNtwo {
    private Logger logger = LoggerFactory.getLogger(RxCousResultProduce.class);

    /**
     * 使用JmsListener配置消费者监听的队列
     *
     * @param text 接收到的消息
     */
    @JmsListener(destination = "suimh_queue")
    public void receiveQueue(String text) {
        logger.info("RxCousResultProduce : 从suimh_queue队列收到的回复报文为:" + text);
    }

/**
 *topic方式接收消息
 *
 */
    @JmsListener(destination = "ac-topic",containerFactory = "jmsTopicListenerContainerFactory")
    public void receiveTopic(String text) {
            logger.info("RxCousResultProduce : 从ac-topic队列收到的回复报文为:" + text);
    }
}

6、创建测试类ActiveMQTest

package com.example.shiroredis.test;

import com.example.shiroredis.activemq.MessageProduce;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.jms.Destination;

@Controller
public class ActiveMQTest {

    @Resource
    MessageProduce messageProduce;

    @GetMapping(value = "/activeMqSendMes")
    @ResponseBody
    public String activeMqSendMes() {
        int num = 10;
        try {
                //ActiveMQQueue 队列模式
                //ActiveMQTopic 订阅模式
                Destination destinationQueue = new ActiveMQQueue("suimh-queue");
                Destination destinationTopic  = new ActiveMQTopic("ac-topic");
/*                for (int i = 1; i <= num; i++) {
                    messageProduce.convertAndSend(destinationQueue, "这是queue发送的第" + i + "个消息!");
                    messageProduce.convertAndSend(destinationTopic,"这是topic发送的第" + i + "个消息!");
                }*/
                messageProduce.convertAndSend(destinationQueue, "这是queue发送的消息!");
                messageProduce.convertAndSend(destinationTopic,"这是topic发送的消息!");
                return "activeMQ生产成功!";
            } catch (Exception e) {
                e.printStackTrace();
                return "activeMQ生产失败!";
            }
    }
}

源码地址:https://github.com/xikai56/shiroDemo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值