【RabbitMQ】06 Spring整合RabbitMQ

 

首先生产者和消费者需要的Maven依赖是一样的

<?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">
    <parent>
        <artifactId>RabbitMQ</artifactId>
        <groupId>cn.dzz</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Spring-RabbitMQ-Producer</artifactId>

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

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

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.10</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

</project>

其次的RabbitMQ连接信息也是一致的

rabbitmq.properties

rabbitmq.host = 192.168.2.121 # 换成你的ip
rabbitmq.port = 5672
rabbitmq.username = test # 你的账号和密码
rabbitmq.password = 123456 # 你的账号和密码
rabbitmq.virtual-host = /dzz # 你设置的虚拟主机

 

生产者服务Spring整合:

生产者定义的Spring.xml文件(文件名随意 这里我取的是producer-config.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"
       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}"
                               publisher-confirms="true"
                               publisher-returns="true"
    />
    <!--定义管理交换机、队列-->
    <rabbit:admin connection-factory="connectionFactory"/>

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

    <!-- 简单模式队列 不存在时自动创建 交换机默认DIRECT 名字 “” 路由键就是队列的名称  -->
    <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 name="spring-fanout-exchange" id="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>

    <!-- 通配符Topic模式队列 -->
    <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 name="spring-topic-exchange" id="spring-topic-exchange" auto-declare="true">
        <rabbit:bindings>
            <rabbit:binding pattern="heima.*" queue="spring-topic-queue-1"/>
            <rabbit:binding pattern="heima.#" queue="spring-topic-queue-2"/>
            <rabbit:binding pattern="itcast.#" queue="spring-topic-queue-3"/>
        </rabbit:bindings>
    </rabbit:topic-exchange>

</beans>

然后编写对应的测试类:

注意测试类编写要注入xml文件,文件名称别写错

package cn.dzz;

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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:producer-config.xml")
public class SpringProducerTest {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 简单模式消息发送
     */
    @Test
    public void simpleTest() {
        rabbitTemplate.convertAndSend("spring-queue", "hello spring integrate rabbitmq ....");
    }

    /**
     * fanout广播订阅消息发送
     */
    @Test
    public void fanoutTest() {
        rabbitTemplate.convertAndSend("spring-fanout-exchange", "", "hello spring integrate rabbitmq ....");
    }

    /**
     * topic通配符消息发送
     */
    @Test
    public void topicTest() {
        rabbitTemplate.convertAndSend("spring-topic-exchange", "itcast.info", "hello spring integrate rabbitmq ....");
    }
}

依次执行之后就会在RabbitMQ中加载相应的交换机和队列信息:

 

 

消费者服务Spring整合:

消费者的Spring.xml配置信息(consumer-config.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"
       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}"/>

    <context:component-scan base-package="cn.dzz.rabbitmq.listener" />

    <!--定义监听器容器-->
    <rabbit:listener-container connection-factory="connectionFactory" auto-declare="true">
        <rabbit:listener ref="simpleQueueListener" 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>

这个监听器编写太累了,一个监听器就要写一个类来实现:

其余的广播监听器和通配符监听器都是一样的,不重复贴上来了

package cn.dzz.rabbitmq.listener;

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

import java.nio.charset.StandardCharsets;
@Component
public class SimpleQueueListener implements MessageListener {
    @Override
    public void onMessage(Message message) {

        // 监听到消息之后要触发的回调逻辑
        byte[] body = message.getBody();
        System.out.println("简单模式队列1监听:" + new String(body, StandardCharsets.UTF_8));
    }
}

 

消费者测试类编写:

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

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:consumer-config.xml")
public class SpringConsumerTest {

    @Test
    public void simpleListenerTest() {
        System.out.println("监听测试");
    }
}

这里很奇怪,和视频不太一样,视频里面程序跑起来不需要停止就能收到简单模式的消息

但是在我这里只能在程序结束以后看到:

"C:\Program Files (x86)\Java\jdk1.8.0_291\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2021.2.1\lib\idea_rt.jar=64697:C:\Program Files\JetBrains\IntelliJ IDEA 2021.2.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\JetBrains\IntelliJ IDEA 2021.2.1\lib\idea_rt.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2021.2.1\plugins\junit\lib\junit5-rt.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2021.2.1\plugins\junit\lib\junit-rt.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\charsets.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\deploy.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\access-bridge-32.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\cldrdata.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\dnsns.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\jaccess.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\jfxrt.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\localedata.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\nashorn.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\sunec.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\sunjce_provider.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\sunmscapi.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\sunpkcs11.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\ext\zipfs.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\javaws.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\jce.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\jfr.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\jfxswt.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\jsse.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\management-agent.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\plugin.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\resources.jar;C:\Program Files (x86)\Java\jdk1.8.0_291\jre\lib\rt.jar;C:\Users\Administrator\IdeaProjects\RabbitMQ\Spring-RabbitMQ-Consumer\target\test-classes;C:\Users\Administrator\IdeaProjects\RabbitMQ\Spring-RabbitMQ-Consumer\target\classes;C:\Users\Administrator\.m2\repository\org\springframework\spring-context\5.3.10\spring-context-5.3.10.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-aop\5.3.10\spring-aop-5.3.10.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-beans\5.3.10\spring-beans-5.3.10.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-core\5.3.10\spring-core-5.3.10.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-jcl\5.3.10\spring-jcl-5.3.10.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-expression\5.3.10\spring-expression-5.3.10.jar;C:\Users\Administrator\.m2\repository\org\springframework\amqp\spring-rabbit\2.1.8.RELEASE\spring-rabbit-2.1.8.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\amqp\spring-amqp\2.1.8.RELEASE\spring-amqp-2.1.8.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\retry\spring-retry\1.2.4.RELEASE\spring-retry-1.2.4.RELEASE.jar;C:\Users\Administrator\.m2\repository\com\rabbitmq\amqp-client\5.4.3\amqp-client-5.4.3.jar;C:\Users\Administrator\.m2\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-messaging\5.1.9.RELEASE\spring-messaging-5.1.9.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-tx\5.1.9.RELEASE\spring-tx-5.1.9.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-test\5.3.10\spring-test-5.3.10.jar;C:\Users\Administrator\.m2\repository\junit\junit\4.13.2\junit-4.13.2.jar;C:\Users\Administrator\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 SpringConsumerTest,simpleListenerTest
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
广播模式队列1监听:hello spring integrate rabbitmq ....
简单模式队列1监听:hello spring integrate rabbitmq ....
广播模式队列2监听:hello spring integrate rabbitmq ....
Topic通配符模式队列3监听:hello spring integrate rabbitmq ....
监听测试

Process finished with exit code 0

 

posted @ 2021-10-07 09:59  emdzz  阅读(44)  评论(0编辑  收藏  举报