springboot集成activeMQ

消息队列中间件是分布式系统中重要的组件,主要解决应用耦合,异步消息,流量削锋等问题,以下就简单介绍springboot集成activeMQ的步骤。

1、下载activeMQ,解压吗,进入bin目录下,根据电脑配置选择win32或者win64,双击即可启动

2、新建springboot项目,并添加如下依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <!--springboot2.0.*版本采用这个-->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-pool</artifactId>
        </dependency>

        <!-- springboot2.1.* 采用如下连接池依赖
        <dependency>
            <groupId>org.messaginghub</groupId>
            <artifactId>pooled-jms</artifactId>
        </dependency>-->

3、配置application.properties:

#增加activemq配置
#ActiveMQ通讯地址
spring.activemq.broker-url=failover:(tcp://127.0.0.1:61616)
# 默认代理URL是否应该在内存中。如果指定了显式代理,则忽略此值
spring.activemq.in-memory=true
spring.activemq.user=admin
spring.activemq.password=123456
# 等待消息发送响应的时间。设置为0等待永远。
spring.activemq.send-timeout=0
#默认情况下activemq提供的是queue模式,若要使用topic模式需要配置下面配置
#spring.jms.pub-sub-domain=false
#信任所有的包
spring.activemq.packages.trust-all=true
#启用连接池,使用ActiveMQ的连接池需引入的依赖
spring.activemq.pool.enabled=true
#连接池最大连接数
spring.activemq.pool.max-connections=10
#每个连接的有效会话的最大数目
spring.activemq.pool.max-sessions-per-connection=1000
#空闲的连接过期时间,15秒
spring.activemq.pool.idle-timeout=15000
#连接过期超时
spring.activemq.pool.expiry-timeou=20000
#当连接请求和池满时是否阻塞,设置false会抛“JMSException异常”。
spring.activemq.pool.block-if-full=false

4、添加消息中心配置类,此配置定义了链接工厂以及发送与接收模板的bean,可以在主项目中直接注入使用。配置了queue和topic两种bean,可以同时开启两种消息模式,如下:

package net.cnki.activemq.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.util.backoff.FixedBackOff;

import javax.jms.ConnectionFactory;

@Configuration
public class ActiveMQConfig {

    //目的地
    public final static String JMS_LISTENER_CONTAINER_FACTORY_QUEUE = "jmsListenerContainerFactoryQueue";

    public final static String JMS_LISTENER_CONTAINER_FACTORY_TOPIC = "jmsListenerContainerFactoryTopic";

    public final static String JMS_QUEUE = "jmsQueue";

    public final static String JMS_TOPIC = "jmsTopic";

    @Bean(JMS_LISTENER_CONTAINER_FACTORY_TOPIC)
    public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ConnectionFactory activeMQConnectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setBackOff(getFbo(5));
        factory.setPubSubDomain(true);
        factory.setConnectionFactory(activeMQConnectionFactory);
        return factory;
    }

    @Bean(JMS_LISTENER_CONTAINER_FACTORY_QUEUE)
    public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ConnectionFactory activeMQConnectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        //factory.setBackOff(getFbo(5));
        factory.setPubSubDomain(false);
        factory.setConnectionFactory(activeMQConnectionFactory);
        return factory;
    }

    /**
     * 当MQ服务连不上时,设置最大尝试次数,以免频繁尝试连接,从而造成服务器压力
     * @param maxAttempts
     * @return
     */
    public FixedBackOff getFbo(int maxAttempts) {
        FixedBackOff fbo = new FixedBackOff();
        fbo.setMaxAttempts(maxAttempts);
        return fbo;
    }

}

5、添加生产者和消费者

生产者(模拟前台发送消息,定义topic和queue生产者各一个):

	@RequestMapping("/producer")
	@ResponseBody
	public String producer(String logContent) {
		jmsTemplate.convertAndSend(new ActiveMQTopic(ActiveMQConfig.JMS_TOPIC), logContent);//消息队列同步数据
		jmsTemplate.convertAndSend(new ActiveMQQueue(ActiveMQConfig.JMS_QUEUE), logContent);//消息队列同步数据
		return "";
	}

消费者(topic和queue消费者各定义两个,用以观察两者区别):

	@JmsListener(destination = ActiveMQConfig.JMS_TOPIC, containerFactory = ActiveMQConfig.JMS_LISTENER_CONTAINER_FACTORY_TOPIC)
	public void consumerOne(String str) throws Exception {
		System.out.println("topic消费者1:"+str);
	}
	@JmsListener(destination = ActiveMQConfig.JMS_TOPIC, containerFactory = ActiveMQConfig.JMS_LISTENER_CONTAINER_FACTORY_TOPIC)
	public void consumerTwo(String str) throws Exception {
		System.out.println("topic消费者2:"+str);
	}
	@JmsListener(destination = ActiveMQConfig.JMS_QUEUE, containerFactory = ActiveMQConfig.JMS_LISTENER_CONTAINER_FACTORY_QUEUE)
	public void consumerThree(String str) throws Exception {
		System.out.println("queue消费者1:"+str);
	}
	@JmsListener(destination = ActiveMQConfig.JMS_QUEUE, containerFactory = ActiveMQConfig.JMS_LISTENER_CONTAINER_FACTORY_QUEUE)
	public void consumerFour(String str) throws Exception {
		System.out.println("queue消费者2:"+str);
	}

6、发送消息测试,结果如下:

 queue和topic区别:

  1. 是否需要提前订阅
    队列模式:消费者不需要提前订阅也可以消费消息
    主题模式:只有提前进行订阅的消费者才能成功消费消息
  2. 多个消费者如何分配消息
    队列模式:只能平均消费消息,被别的消费者消费的消息不能重复被其他的消费者消费
    主题模式:每个订阅者都可以消费主题模式中的每一条消息
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot 集成 ActiveMQ 很简单,只需要在项目的 pom.xml 文件中添加 ActiveMQ 的依赖,然后在配置文件 application.properties 中配置 ActiveMQ 的地址即可。具体步骤如下: 1. 在 pom.xml 文件中添加 ActiveMQ 的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> ``` 2. 在 application.properties 文件中配置 ActiveMQ 的地址,例如: ``` spring.activemq.broker-url=tcp://localhost:61616 ``` 3. 在启动类中添加 @EnableJms 注解,表示启用 JMS。 4. 创建一个 JmsTemplate 对象来发送和接收消息。 完成以上步骤即可在 Spring Boot 中使用 ActiveMQ。 ### 回答2: Spring Boot是Spring Framework的一个用于简化Spring应用程序开发和部署的框架。它提供了一种简单的方式来开发、构建和运行Spring应用程序,同时也能方便地集成其他框架和技术。 ActiveMQ是一个流行的开源消息代理,它支持多种协议和编程语言,包括Java、C#、C++、Python等。它提供了可靠的消息传递机制,可以用于构建分布式系统和异步消息处理应用。 Spring Boot提供了对ActiveMQ集成支持,可以通过在pom.xml文件中添加相关依赖和配置,实现快速集成和使用ActiveMQ。 下面是详细的步骤: 1. 在pom.xml文件中添加ActiveMQ的依赖: ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> </dependencies> ``` 2. 在application.properties文件中添加ActiveMQ的配置: ``` spring.activemq.broker-url=tcp://localhost:61616 spring.activemq.user=admin spring.activemq.password=admin ``` 其中broker-url是ActiveMQ的连接地址,user和password是登录信息。 3. 在代码中使用JmsTemplate发送和接收消息: ``` @Service public class MessageService { @Autowired private JmsTemplate jmsTemplate; public void sendMessage(String message) { jmsTemplate.send("test.queue", new MessageCreator() { public Message createMessage(Session session) throws JMSException { return session.createTextMessage(message); } }); } @JmsListener(destination = "test.queue") public void receiveMessage(String message) { System.out.println("Received message: " + message); } } ``` 上面的代码定义了一个MessageService类,里面包含了一个sendMesssge方法和一个receiveMessage方法。sendMessage方法将消息发送到名为“test.queue”的队列中,而receiveMessage方法则监听该队列并接收消息。 在使用JmsTemplate发送消息时,需要提供消息的目的地和消息内容。这里使用createTextMessage方法创建一个文本消息,并将其发送到指定的队列中。 在使用@JmsListener注解接收消息时,需要指定监听的队列名称和接收消息的方法。接收到消息后,将会调用该方法并输出消息内容。 4. 运行应用程序并测试消息发送和接收功能。 启动应用程序后,调用MessageService的sendMessage方法即可发送消息到ActiveMQ,同时在控制台输出了接收到的消息。这样,就成功地实现了Spring Boot和ActiveMQ集成。 总之,通过以上步骤,我们可以很容易地将Spring Boot和ActiveMQ进行集成,在开发分布式系统和消息处理应用时,能够方便地使用ActiveMQ提供的可靠消息传递机制。 ### 回答3: Spring Boot是一种基于Spring框架的快速开发框架,它提供了很多便捷快捷的特性。ActiveMQ则是一种高性能、开源的消息传递中间件。Spring Boot和ActiveMQ的结合,能够搭建一个可插拔、可扩展、可重复利用的消息解决方案。下面将介绍如何在Spring Boot中集成ActiveMQ。 1、引入所需依赖 首先需要在项目中引入ActiveMQ相关的依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> 2、配置ActiveMQ 在application.properties文件中配置ActiveMQ,如下所示: #ActiveMQ configuration spring.activemq.broker-url=tcp://localhost:61616 spring.activemq.user=admin spring.activemq.password=admin spring.jms.template.default-destination=test-queue spring.jms.listener.auto-startup=true 其中,spring.activemq.broker-url指定了ActiveMQ服务器的地址;spring.activemq.user和spring.activemq.password是登录ActiveMQ服务器的用户名和密码;spring.jms.template.default-destination设置了默认的目的地队列;spring.jms.listener.auto-startup设置消息监听器的自动启动。 3、编写消息生产者代码 @Inject private JmsMessagingTemplate jmsMessagingTemplate; public void produceMessage(String message) { jmsMessagingTemplate.convertAndSend("test-queue", message); } 首先在类中注入JmsMessagingTemplate,它是Spring Boot提供的用于发送消息的工具类。然后编写produceMessage()方法,将消息发送到目的地队列test-queue中。 4、编写消息消费者代码 @JmsListener(destination="test-queue") public void receiveMessage(String message) { System.out.println("Received message: " + message); } 使用@JmsListener注解,在方法上指定监听的目的地队列为test-queue。当有消息到达test-queue时,就会自动调用receiveMessage()方法,进行消息处理。 通过上述步骤,就可以在Spring Boot中集成ActiveMQ,实现消息生产者和消息消费者的功能。当然,还可以通过其他方式来实现集成,例如使用ConnectionFactory或者JmsTemplate等Spring集成方式。这样就能够应用在更多的项目中,提高应用的可靠性和可扩展性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值