9-Spring 整合 RabbitMQ

2022-11-22 09:57:40 浏览数 (1)

9-Spring 整合 RabbitMQ

1. 搭建生产者工程

1.1 创建工程

创建一个空的 maven 工程 spring-rabbitmq-producer:

1.2. 添加依赖

修改pom.xml文件内容为如下:

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lijw</groupId>
    <artifactId>spring-rabbitmq-producer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit</artifactId>
            <version>2.1.8.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>
    </dependencies>

</project>

1.3. 配置整合

  1. 创建spring-rabbitmq-producersrcmainresourcespropertiesrabbitmq.properties连接参数等配置文件;
代码语言:javascript复制
rabbitmq.host=127.0.0.1
rabbitmq.port=5672
rabbitmq.username=libai
rabbitmq.password=libai
rabbitmq.virtual-host=/test
  1. 创建 spring-rabbitmq-producersrcmainresourcesspringspring-rabbitmq.xml 整合配置文件;
代码语言:javascript复制
<?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"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/rabbit
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
    <!--加载配置文件-->
    <context:property-placeholder location="classpath:rabbitmq.properties"/>

    <!-- 定义rabbitmq connectionFactory -->
    <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                               port="${rabbitmq.port}"
                               username="${rabbitmq.username}"
                               password="${rabbitmq.password}"
                               virtual-host="${rabbitmq.virtual-host}"/>
    <!--定义管理交换机、队列-->
    <rabbit:admin connection-factory="connectionFactory"/>

    <!--定义持久化队列,不存在则自动创建;不绑定到交换机则绑定到默认交换机
    默认交换机类型为direct,名字为:"",路由键为队列的名称
    -->
    <!--
        id:bean的名称
        name:queue的名称
        auto-declare:自动创建
        auto-delete:自动删除。 最后一个消费者和该队列断开连接后,自动删除队列
        exclusive:是否独占
        durable:是否持久化
    -->
    <rabbit:queue id="spring_queue" name="spring_queue"    auto-declare="true"/>

    <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~广播;所有队列都能收到消息~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_fanout_queue_1" name="spring_fanout_queue_1" auto-declare="true"/>

    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_fanout_queue_2" name="spring_fanout_queue_2" auto-declare="true"/>

    <!--定义广播类型交换机;并绑定上述两个队列-->
    <rabbit:fanout-exchange id="spring_fanout_exchange" name="spring_fanout_exchange"  auto-declare="true">
        <rabbit:bindings>
            <rabbit:binding  queue="spring_fanout_queue_1"  />
            <rabbit:binding queue="spring_fanout_queue_2"/>
        </rabbit:bindings>
    </rabbit:fanout-exchange>

    <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~通配符;*匹配一个单词,#匹配多个单词 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_topic_queue_1" name="spring_topic_queue_1"  auto-declare="true"/>
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_topic_queue_2" name="spring_topic_queue_2" auto-declare="true"/>
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_topic_queue_3" name="spring_topic_queue_3" auto-declare="true"/>

    <rabbit:topic-exchange id="spring_topic_exchange"  name="spring_topic_exchange" auto-declare="true">
        <rabbit:bindings>
            <rabbit:binding pattern="item.insert"  queue="spring_topic_queue_1"/>
            <rabbit:binding pattern="item.update" queue="spring_topic_queue_1"/>
            <rabbit:binding pattern="item.*" queue="spring_topic_queue_2"/>
            <rabbit:binding pattern="item.#" queue="spring_topic_queue_3"/>
        </rabbit:bindings>
    </rabbit:topic-exchange>

    <!--定义rabbitTemplate对象操作可以在代码中方便发送消息-->
    <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
</beans> 

1.4. 发送消息

创建测试文件 spring-rabbitmq-producersrctestjavacomlijwrabbitmqProducerTest.java

代码语言:javascript复制
package com.lijw;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author Aron.li
 * @date 2022/3/3 15:32
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-rabbitmq-producer.xml")
public class ProducerTest {

    //1. 注入 RabbitTemplate
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //2. 简单模式:发送消息
    @Test
    public void testHelloWorld(){
        rabbitTemplate.convertAndSend("spring_queue", "hello world spring....");
    }

    //3. 订阅发布模块: 发送fanout消息
    @Test
    public void testFanout(){
        rabbitTemplate.convertAndSend("spring_fanout_exchange","","spring fanout msg.....");
    }

    //4. Topics通配符模式: 发送topic消息
    @Test
    public void testTopics(){
        rabbitTemplate.convertAndSend("spring_topic_exchange", "item.insert", "新增了商品。Topic模式;routing key 为 item.insert");
        rabbitTemplate.convertAndSend("spring_topic_exchange", "item.update", "修改了商品。Topic模式;routing key 为 item.update");
        rabbitTemplate.convertAndSend("spring_topic_exchange", "item.delete", "删除了商品。Topic模式;routing key 为 item.delete");
        rabbitTemplate.convertAndSend("spring_topic_exchange", "item.deploy.version", "发布了商品。Topic模式;routing key 为 item.deploy.version");
    }
}

执行发送消息后,我们在管理页面查看创建的队列消息:

2. 搭建消费者工程

2.1. 创建工程

创建一个空的 maven 工程 spring-rabbitmq-consumer:

2.2. 添加依赖

修改pom.xml文件内容为如下:

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lijw</groupId>
    <artifactId>spring-rabbitmq-consumer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit</artifactId>
            <version>2.1.8.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>
    </dependencies>

</project>

2.3. 配置整合

  1. 创建spring-rabbitmq-consumersrcmainresourcespropertiesrabbitmq.properties连接参数等配置文件;
代码语言:javascript复制
rabbitmq.host=127.0.0.1
rabbitmq.port=5672
rabbitmq.username=libai
rabbitmq.password=libai
rabbitmq.virtual-host=/test
  1. 创建 spring-rabbitmq-consumersrcmainresourcesspringspring-rabbitmq-consumer.xml 整合配置文件;
代码语言:javascript复制
<?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"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/rabbit
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
    <!--加载配置文件-->
    <context:property-placeholder location="classpath:rabbitmq.properties"/>

    <!-- 定义rabbitmq connectionFactory -->
    <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                               port="${rabbitmq.port}"
                               username="${rabbitmq.username}"
                               password="${rabbitmq.password}"
                               virtual-host="${rabbitmq.virtual-host}"/>

    <!--  定义消息监听器  -->
    <bean id="springQueueListener" class="com.lijw.consumer.listener.SpringQueueListener"/>
    <bean id="fanoutListener1" class="com.lijw.consumer.listener.FanoutListener1"/>
    <bean id="fanoutListener2" class="com.lijw.consumer.listener.FanoutListener2"/>
    <bean id="topicListener1" class="com.lijw.consumer.listener.TopicListener1"/>
    <bean id="topicListener2" class="com.lijw.consumer.listener.TopicListener2"/>
    <bean id="topicListener3" class="com.lijw.consumer.listener.TopicListener3"/>

    <!--  定义监听器与队列的绑定  -->
    <rabbit:listener-container connection-factory="connectionFactory" auto-declare="true">
        <rabbit:listener ref="springQueueListener" queue-names="spring_queue"/>
        <rabbit:listener ref="fanoutListener1" queue-names="spring_fanout_queue_1"/>
        <rabbit:listener ref="fanoutListener2" queue-names="spring_fanout_queue_2"/>
        <rabbit:listener ref="topicListener1" queue-names="spring_topic_queue_1"/>
        <rabbit:listener ref="topicListener2" queue-names="spring_topic_queue_2"/>
        <rabbit:listener ref="topicListener3" queue-names="spring_topic_queue_3"/>
    </rabbit:listener-container>
</beans>

2.4. 消息监听器

集成spring框架,需要实现 MessageListener 接口来读取队列的消息,对于各类消息队列,则写上对应的监听器类:

1)队列监听器

“监听简单模式的队列消息 ”

代码语言:javascript复制
package com.lijw.consumer.listener;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

import java.nio.charset.StandardCharsets;

/**
 * 队列监听器
 *
 * @author Aron.li
 * @date 2022/3/3 21:25
 */
public class SpringQueueListener implements MessageListener {

    //1. 简单模块:队列消息消费
    @Override
    public void onMessage(Message message) {

        String msg = new String(message.getBody(), StandardCharsets.UTF_8);

        System.out.printf("接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s n",
                message.getMessageProperties().getReceivedExchange(),
                message.getMessageProperties().getReceivedRoutingKey(),
                message.getMessageProperties().getConsumerQueue(),
                msg);

    }

}
2)广播监听器1
代码语言:javascript复制
package com.lijw.consumer.listener;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import java.nio.charset.StandardCharsets;

/**
 * @author Aron.li
 * @date 2022/3/3 21:34
 */
public class FanoutListener1 implements MessageListener {
    @Override
    public void onMessage(Message message) {
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.printf("广播监听器1:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s n",
                message.getMessageProperties().getReceivedExchange(),
                message.getMessageProperties().getReceivedRoutingKey(),
                message.getMessageProperties().getConsumerQueue(),
                msg);
    }
}
3)广播监听器2
代码语言:javascript复制
package com.lijw.consumer.listener;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

import java.nio.charset.StandardCharsets;

/**
 * @author Aron.li
 * @date 2022/3/3 21:34
 */
public class FanoutListener2 implements MessageListener {
    @Override
    public void onMessage(Message message) {
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.printf("广播监听器2:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s n",
                message.getMessageProperties().getReceivedExchange(),
                message.getMessageProperties().getReceivedRoutingKey(),
                message.getMessageProperties().getConsumerQueue(),
                msg);
    }
}
4)Topic 通配符监听器 1
代码语言:javascript复制
package com.lijw.consumer.listener;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

import java.nio.charset.StandardCharsets;

/**
 * @author Aron.li
 * @date 2022/3/3 21:34
 */
public class TopicListener1 implements MessageListener {
    @Override
    public void onMessage(Message message) {
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.printf("Topic监听器1:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s n",
                message.getMessageProperties().getReceivedExchange(),
                message.getMessageProperties().getReceivedRoutingKey(),
                message.getMessageProperties().getConsumerQueue(),
                msg);
    }
}
5)Topic 通配符监听器 2
代码语言:javascript复制
package com.lijw.consumer.listener;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

import java.nio.charset.StandardCharsets;

/**
 * @author Aron.li
 * @date 2022/3/3 21:34
 */
public class TopicListener2 implements MessageListener {
    @Override
    public void onMessage(Message message) {
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.printf("Topic监听器2:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s n",
                message.getMessageProperties().getReceivedExchange(),
                message.getMessageProperties().getReceivedRoutingKey(),
                message.getMessageProperties().getConsumerQueue(),
                msg);
    }
}
6)Topic 通配符监听器 3
代码语言:javascript复制
package com.lijw.consumer.listener;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

import java.nio.charset.StandardCharsets;

/**
 * @author Aron.li
 * @date 2022/3/3 21:34
 */
public class TopicListener3 implements MessageListener {
    @Override
    public void onMessage(Message message) {
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.printf("Topic监听器3:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s n",
                message.getMessageProperties().getReceivedExchange(),
                message.getMessageProperties().getReceivedRoutingKey(),
                message.getMessageProperties().getConsumerQueue(),
                msg);
    }
}

2.5. 编写测试方法

如果需要测试启用监听器,我们可以通过集成Spring的单元测试,写一个循环触发Spring框架的执行,如下:

代码语言:javascript复制
package com.lijw.consumer;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author Aron.li
 * @date 2022/3/3 21:30
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-rabbitmq-consumer.xml")
public class ConsumerTest {

    @Test
    public void test1(){
        boolean flag = true;
        while (true){

        }
    }
}

3.测试

3.1 运行消费者工程的测试方法,启动各类监听器

3.2 启动生产者的测试方法,发送消息至队列中

可以看到成功接收到各类消息了。

0 人点赞