使用gradle搭建Spring+ActiveMQ的demo步骤

使用 gradle 搭建 spring + ActiveMQ 的一个 demo

参考:https://juejin.im/post/5ad46f34518825651d08265c#heading-15
https://www.imooc.com/learn/856

第一个是掘金的一篇文章,第二个是慕课网上的一个视频课程。


以下是使用 gradle 搭建 spring + ActiveMQ 的一个 demo 的步骤

1.下载 ActiveMQ

首先去 ActiveMQ 官网下载 ActiveMQ 软件,官网地址:https://activemq.apache.org/

2.引入依赖

创建一个新的 ActiveMQ 项目,并在 build.gradle 中引入相关的依赖

// https://mvnrepository.com/artifact/org.springframework/spring-context
compile group: 'org.springframework', name: 'spring-context', version: '5.1.9.RELEASE'
// https://mvnrepository.com/artifact/org.apache.activemq/activemq-all
compile group: 'org.apache.activemq', name: 'activemq-all', version: '5.15.9'
// https://mvnrepository.com/artifact/org.apache.activemq/activemq-pool
compile group: 'org.apache.activemq', name: 'activemq-pool', version: '5.15.9'
// https://mvnrepository.com/artifact/org.springframework/spring-jms
compile group: 'org.springframework', name: 'spring-jms', version: '5.1.9.RELEASE'

3.开始写代码

3.1 队列模式
3.1.1 创建消息消费者

为了观察队列模式的特点,这里我创建了两个队列模式的消费者,其实是自定义两个消息监听器,让其实现 MessageListener 接口,重写 onMessage() 方法。代码如下:

package com.caihao.activemqdemo.consumer;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
/**
 * 队列模式-消息消费者1
 */
public class QueueListener1 implements MessageListener{

  @Override
  public void onMessage(Message message) {
    // 由于我这里只负责接收TextMessage类型,因此做一个类型判断
    if (message instanceof TextMessage){
      TextMessage textMessage = (TextMessage) message;
      try {
        System.out.println("队列模式消费者1:"+textMessage.getText());
      } catch (JMSException e) {
        e.printStackTrace();
      }
    }
  }
}

由于这两个消息监听器类代码类似,因此就不放出另一个类了。

3.1.2 配置spring和activeMQ

在项目的 resources 资源环境目录下新建一个 spring 的 xml 配置文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  <!--生产者和消费者都需要用到的-start-->
  <!--配置包扫描路径-->
  <context:component-scan base-package="com.caihao.activemqdemo.producer"/>
  <context:component-scan base-package="com.caihao.activemqdemo.consumer"/>

  <!--ActiveMQ为我们提供的ConnectionFactory-->
  <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
    <property name="brokerURL" value="tcp://localhost:61616"/>
  </bean>
  <!--spring jms 为我们提供的连接池,这个connectionFactory也是下面的jmsTemplate要使用的,
  它其实就是对activeMQ的ConnectionFactory的一个封装-->
  <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
    <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
  </bean>

  <!--提供一个队列模式的目的地,点对点的-->
  <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
    <!--目的地队列的名字-->
    <constructor-arg value="queue-demo"/>
  </bean>
  <!--生产者和消费者都需要用到的-end-->

  <!--生产者所需要的-start-->
  <!--配置jmsTemplate用于发送消息-->
  <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory"/>
  </bean>
  <!--生产者所需要的-end-->

  <!--消费者所需要的start-->
  <!--配置消息监听器1,即消息的消费者-->
  <bean id="queueListener1" class="com.caihao.activemqdemo.consumer.QueueListener1"/>
  <!--配置消息容器1-->
  <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <!--指定连接工厂-->
    <property name="connectionFactory" ref="connectionFactory"/>
    <!--指定消息目的地-->
    <property name="destination" ref="queueDestination"/>
    <!--指定消息监听器-->
    <property name="messageListener" ref="queueListener1"/>
  </bean>
  <!--配置消息监听器2,即消息的消费者-->
  <bean id="queueListener2" class="com.caihao.activemqdemo.consumer.QueueListener2"/>
  <!--配置消息容器2-->
  <bean id="jmsContainer2" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <!--指定连接工厂-->
    <property name="connectionFactory" ref="connectionFactory"/>
    <!--指定消息目的地-->
    <property name="destination" ref="queueDestination"/>
    <!--指定消息监听器-->
    <property name="messageListener" ref="queueListener2"/>
  </bean>
  <!--消费者所需要的end-->

</beans>

具体的解释已经写在代码中了,这里说一下,由于我是打算用两个队列模式的消息监听器,因此,在配置文件中我需要配置两个消息监听器和消息容器。其次就是,如果我们需要把生产者和消费者分开配置的话,则只需要按照我所注释的生产者/消费者/公共的/start-end 进行划分即可。

3.1.3 创建消息生产者

这里,我们新建一个类叫 Producer,提供一个方法,在方法里面通过 jmsTemplate 进行发送消息。其中里面的 queueDestination 为上面的 xml 配置文件中的 queueDestination,这里我们不能使用 Autowired 注解,因为他们的类型不一样,我们需要通过 Resources 注解的 name 属性来进行指定。

package com.caihao.activemqdemo.producer;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

/**
 * 消息生产者
 */
@Component
public class Producer {

  @Autowired
  private JmsTemplate jmsTemplate;
  @Resource(name = "queueDestination")
  private Destination queueDestination;

  /**
   * 发送队列消息
   */
  public void sendQueueMessage(String message) {
    // 发送消息
    jmsTemplate.send(queueDestination, new MessageCreator() {
      @Override
      public Message createMessage(Session session) throws JMSException {
        // 返回创建的消息
        return session.createTextMessage(message);
      }
    });
  }
}
3.1.4 运行测试代码

生产者、消费者和配置文件都写好之后就可以开始写测试代码了。这里我们定义一个普通 java 类来运行代码。在 main 方法中首先进行配置文件的加载,然后获取生产者实例,接着调用生产者实例发送消息。

package com.caihao.activemqdemo;

import com.caihao.activemqdemo.producer.Producer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {

  public static void main(String[] args) {
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("spring-activemq.xml");
    // 获取生产者实例
    Producer producer = (Producer) ac.getBean("producer");
    for (int i = 0; i < 100; i++) {
      // 发送队列消息
      producer.sendQueueMessage("hello" + i);
    }
    // ac.close();
  }
}

在运行测试代码之前,还需要先将之前下载的 ActiveMQ 启动起来。找到 ActiveMQ 解压后的 bin 目录,然后根据操作系统选择 64 还是 32 位,然后运行 win64/win32 中的 activemq.bat 。当在启动的窗口日志中看到类似 http://0.0.0.0:8161/的时候,说明 activemq 启动起来了。这个时候,打开浏览器访问 http://127.0.0.1:8161/即可打开activemq的管理界面。然后点击 Manager ActiveMQ broker会弹出一个框让输入用户名和密码,activemq 的用户名和密码都是 admin 。之后运行测试代码,就能在 activemq 的管理界面的导航栏中 Queues 一栏中看到消息队列的相关信息了。控制台也会打印出消费者所消费的信息,观察两个消费者所消费消息的规律,可以看到,它们基本上是一个消费者消费一条消息。一条消息被一个消费者消费了就不能再被另一个消费者所消费。另外,如果只启动了消息的生产者进行发送消息,而消费者一个都没启动的话,消息生产者发送的消息会被存在消息队列中,不会丢失,等到后面启动了消费者之后,消费者还能自动去消息队列里面进行消费消息。

3.2 topic模式

广播模式步骤和上面的队列模式步骤类似。

3.2.1 创建消息消费者

在上面项目的基础上,我再创建两个消息的消费者,这次的消息消费者是 Topic 模式消费者,除了类名和队列模式消费者不一样,内容基本一致。代码如下。

package com.caihao.activemqdemo.consumer;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * topic模式消费者1
 */
public class TopicListener1 implements MessageListener {

  @Override
  public void onMessage(Message message) {
    if (message instanceof TextMessage) {
      TextMessage textMessage = (TextMessage) message;
      try {
        System.out.println("topic模式消费者1:" + textMessage.getText());
      } catch (JMSException e) {
        e.printStackTrace();
      }
    }
  }
}

第二个消费者类就不贴出了。

3.2.2 配置 spring 和 activemq

这里我还是在之前新建的 spring-activemq.xml 中进行追加配置。首先配置 topic 模式的目的地。由于这个东西需要在生产者和消费者中都有用到,因此我将其放在生产者/消费者公共部分的 start/end 里面。

<!--提供一个topic模式的目的地,广播的-->
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
	<!--topic模式名称-->
	<constructor-arg value="topic-demo"/>
</bean>

然后接着配置消息监听器,这一部分,配置在消费者的 start/end 里面就可以了。

<!--topic模式监听器-->
<!--配置消息监听器1,即消息的消费者-->
<bean id="topicListener1" class="com.caihao.activemqdemo.consumer.TopicListener1"/>
<!--配置消息容器1-->
<bean id="topicContainer1" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <!--指定连接工厂-->
    <property name="connectionFactory" ref="connectionFactory"/>
    <!--指定消息目的地-->
    <property name="destination" ref="topicDestination"/>
    <!--指定消息监听器-->
    <property name="messageListener" ref="topicListener1"/>
</bean>
<!--配置消息监听器2,即消息的消费者-->
<bean id="topicListener2" class="com.caihao.activemqdemo.consumer.TopicListener2"/>
<!--配置消息容器1-->
<bean id="topicContainer2" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <!--指定连接工厂-->
    <property name="connectionFactory" ref="connectionFactory"/>
    <!--指定消息目的地-->
    <property name="destination" ref="topicDestination"/>
    <!--指定消息监听器-->
    <property name="messageListener" ref="topicListener2"/>
</bean>

这样配置就完成了。为了看的明白,我给出 spring-activemq.xml 的全部内容,并将 topic 模式追加的配置进行突出显示。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  <!--生产者和消费者都需要用到的-start-->
  <!--配置包扫描路径-->
  <context:component-scan base-package="com.caihao.activemqdemo.producer"/>
  <context:component-scan base-package="com.caihao.activemqdemo.consumer"/>

  <!--ActiveMQ为我们提供的ConnectionFactory-->
  <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
    <property name="brokerURL" value="tcp://localhost:61616"/>
  </bean>
  <!--spring jms 为我们提供的连接池,这个connectionFactory也是下面的jmsTemplate要使用的,
  它其实就是对activeMQ的ConnectionFactory的一个封装-->
  <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
    <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
  </bean>

  <!--提供一个队列模式的目的地,点对点的-->
  <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
    <!--目的地队列的名字-->
    <constructor-arg value="queue-demo"/>
  </bean>

  <!--提供一个topic模式的目的地,广播的-->
  <bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
    <!--topic模式名称-->
    <constructor-arg value="topic-demo"/>
  </bean>
  <!--生产者和消费者都需要用到的-end-->

  <!--生产者所需要的-start-->
  <!--配置jmsTemplate用于发送消息-->
  <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory"/>
  </bean>
  <!--生产者所需要的-end-->

  <!--消费者所需要的start-->

  <!--配置消息监听器1,即消息的消费者-->
  <bean id="queueListener1" class="com.caihao.activemqdemo.consumer.QueueListener1"/>
  <!--配置消息容器1-->
  <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <!--指定连接工厂-->
    <property name="connectionFactory" ref="connectionFactory"/>
    <!--指定消息目的地-->
    <property name="destination" ref="queueDestination"/>
    <!--指定消息监听器-->
    <property name="messageListener" ref="queueListener1"/>
  </bean>
  <!--配置消息监听器2,即消息的消费者-->
  <bean id="queueListener2" class="com.caihao.activemqdemo.consumer.QueueListener2"/>
  <!--配置消息容器2-->
  <bean id="jmsContainer2" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <!--指定连接工厂-->
    <property name="connectionFactory" ref="connectionFactory"/>
    <!--指定消息目的地-->
    <property name="destination" ref="queueDestination"/>
    <!--指定消息监听器-->
    <property name="messageListener" ref="queueListener2"/>
  </bean>

  <!--topic模式监听器-->
  <!--配置消息监听器1,即消息的消费者-->
  <bean id="topicListener1" class="com.caihao.activemqdemo.consumer.TopicListener1"/>
  <!--配置消息容器1-->
  <bean id="topicContainer1" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <!--指定连接工厂-->
    <property name="connectionFactory" ref="connectionFactory"/>
    <!--指定消息目的地-->
    <property name="destination" ref="topicDestination"/>
    <!--指定消息监听器-->
    <property name="messageListener" ref="topicListener1"/>
  </bean>
  <!--配置消息监听器2,即消息的消费者-->
  <bean id="topicListener2" class="com.caihao.activemqdemo.consumer.TopicListener2"/>
  <!--配置消息容器1-->
  <bean id="topicContainer2" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <!--指定连接工厂-->
    <property name="connectionFactory" ref="connectionFactory"/>
    <!--指定消息目的地-->
    <property name="destination" ref="topicDestination"/>
    <!--指定消息监听器-->
    <property name="messageListener" ref="topicListener2"/>
  </bean>
  <!--消费者所需要的end-->

</beans>
3.2.3 创建消息生产者

这里还是在之前创建的 Producer 的类中追加一个方法发送 topic 模式的消息的方法。内容与 queue 队列模式的差不多,首先引入一个 spring-activemq.xml 文件中定义的 topicDestination,然后通过 jmsTemplate 发送消息(注:这里创建消息这里,我使用了lambda表达式,实际内容其实和之前的创建消息代码是一样的)。

@Resource(name = "topicDestination")
private Destination topicDestination;

/**
 * 发送topic模式消息
 *
 * @param message 消息
 */
public void sendTopicMessage(String message) {
  // 发送消息
  jmsTemplate.send(topicDestination, (session) -> session.createTextMessage(message));
}
3.2.4 运行测试代码

这里,直接修改之前运行队列模式时的 main 方法,在发送消息的时候选择调用sendTopicMessage()方法即可。在运行测试代码之前不要忘了启动 activemq 。通过运行测试代码发现,两个topic消费者都收到了同样的消息,也就是一个消息被这两个消费者同时消费了,就类似于广播,每个监听了该消息队列的监听者都能收到消息。在 activemq 的管理控制台的 topic 界面上也能看到,Messages Enqueued 有100个,而 Message Dequeued 有200个。

topic 模式的特点就是类似于广播,只要是对这个消息队列有监听的人都能收到消息。但是如果是先运行了消息生产者发布消息,而没有提前运行消费者监听消息的话,那么等消息消费者之后启动监听的话,是无法消费之前生产者发送的消息的。其实这也很好理解,就和广播一样,如果你没有提前开启广播,那么广播之前的东西你是收听不到的。

方法,在发送消息的时候选择调用 sendTopicMessage() 方法即可。在运行测试代码之前不要忘了启动 activemq 。通过运行测试代码发现,两个topic 消费者都收到了同样的消息,也就是一个消息被这两个消费者同时消费了,就类似于广播,每个监听了该消息队列的监听者都能收到消息。在 activemq 的管理控制台的 topic 界面上也能看到,Messages Enqueued 有 100 个,而Message Dequeued 有 200 个。

topic 模式的特点就是类似于广播,只要是对这个消息队列有监听的人都能收到消息。但是如果是先运行了消息生产者发布消息,而没有提前运行消费者监听消息的话,那么等消息消费者之后启动监听的话,是无法消费之前生产者发送的消息的。其实这也很好理解,就和广播一样,如果你没有提前开启广播,那么广播之前的东西你是收听不到的。

代码:https://github.com/caiworld/activemq

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值