RabbitMQ之与Spring整合

生活中,最使人疲惫的往往不是道路的遥远,而是心中的郁闷;最使人痛苦的往往不是生活的不幸,而是希望的破灭;最使人颓废的往往不是前途的坎坷,而是自信的丧失;最使人绝望的往往不是挫折的打击,而是心灵的死亡。所以我们要有自己的梦想,让梦想的星光指引着我们走出落漠,走出惆怅,带着我们走进自己的理想。

导读:本篇文章讲解 RabbitMQ之与Spring整合,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

添加依赖

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

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

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

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

创建消息监听器

1.创建队列监听器

public class SpringQueueListener implements MessageListener {
    @Override
    public void onMessage(Message message) {
        try {
            String msg = new String(message.getBody(), "utf-8");
        
            System.out.printf("接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s \n",
                    message.getMessageProperties().getReceivedExchange(),
                    message.getMessageProperties().getReceivedRoutingKey(),
                    message.getMessageProperties().getConsumerQueue(),
                    msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.创建广播监听器

public class FanoutListener1 implements MessageListener {
	@Override
	public void onMessage(Message message) {
		try {
			String msg = new String(message.getBody(), "utf-8");
			
			System.out.printf("广播监听器1:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s \n",
					message.getMessageProperties().getReceivedExchange(),
					message.getMessageProperties().getReceivedRoutingKey(),
					message.getMessageProperties().getConsumerQueue(),
					msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

3.创建通配符监听器

public class TopicListener1 implements MessageListener {
	@Override
	public void onMessage(Message message) {
		try {
			String msg = new String(message.getBody(), "utf-8");
			
			System.out.printf("*号通配符监听器:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s \n",
					message.getMessageProperties().getReceivedExchange(),
					message.getMessageProperties().getReceivedRoutingKey(),
					message.getMessageProperties().getConsumerQueue(),
					msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

配置RabbitMQ

1.创建rabbitmq.properties

创建rabbitmq.properties参数配置文件

rabbitmq.host=ip
rabbitmq.port=5672
rabbitmq.username=test
rabbitmq.password=test
rabbitmq.virtual-host=/test

2.创建生产者配置文件

创建生产者配置文件spring-rabbitmq-producer.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"/>

    <!-- 定义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_direct_queue_1" name="spring_direct_queue_1" auto-declare="true"/>

    <!--定义队列,不存在则自动创建-->
    <rabbit:queue id="spring_direct_queue_2" name="spring_direct_queue_2" auto-declare="true"/>

    <!--定义路由类型交换机;并绑定上述两个队列-->
    <rabbit:direct-exchange name="spring_direct_exchange" >
        <rabbit:bindings>
            <!--direct 类型的交换机绑定队列  key :路由key  queue:队列名称-->
            <rabbit:binding queue="spring_direct_queue_1" key="error"></rabbit:binding>
            <rabbit:binding queue="spring_direct_queue_2" key="info"></rabbit:binding>
        </rabbit:bindings>
    </rabbit:direct-exchange>


    <!--定义队列,不存在则自动创建-->
    <rabbit:queue id="spring_topic_queue1" name="spring_topic_queue1"  auto-declare="true"/>
    <!--定义队列,不存在则自动创建-->
    <rabbit:queue id="spring_topic_queue2" name="spring_topic_queue2" auto-declare="true"/>

	<!--定义通配符类型交换机;并绑定上述两个队列-->
    <rabbit:topic-exchange id="spring_topic_exchange"  name="spring_topic_exchange" auto-declare="true">
        <rabbit:bindings>
            <rabbit:binding pattern="orange.*"  queue="spring_topic_queue1"/>
            <rabbit:binding pattern="old.#" queue="spring_topic_queue2"/>
        </rabbit:bindings>
    </rabbit:topic-exchange>

    <!--定义rabbitTemplate对象-->
    <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
</beans>

3.创建消费者配置文件

创建消费者配置文件spring-rabbitmq-consumer.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"/>

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

	<!-- 创建消费者监听Bean -->
    <bean id="springQueueListener" class="cn.ybzy.rabbitmq.listener.SpringQueueListener"/>
    <bean id="fanoutListener1" class="cn.ybzy.rabbitmq.listener.FanoutListener1"/>
    <bean id="fanoutListener2" class="cn.ybzy.rabbitmq.listener.FanoutListener2"/>
    <bean id="topicListener1" class="cn.ybzy.rabbitmq.listener.TopicListener1"/>
    <bean id="topicListener2" class="cn.ybzy.rabbitmq.listener.TopicListener2"/>

	<!-- 消费者监听与队列的绑定 -->
    <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-container>
</beans>

4.加载rabbitmq配置文件

在spring.xml配置文件中引入rabbitmq配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">


    <import resource="spring-rabbitmq-producer.xml"></import>

    <import resource="spring-rabbitmq-consumer.xml"></import>
</beans>

发送消息测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class ProducerTest {
    
    
    /**
     * 开启消费者监听
     */
    @Test
    public void consumer(){
        while (true){
        
        }
    }
    
    
    //注入 RabbitTemplate
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    /**
     * 发送简单消息
     */
    @Test
    public void testHelloWorld(){
        rabbitTemplate.convertAndSend("spring_queue","spring_queue...");
    }


    /**
     * 发送fanout类型消息
     */
    @Test
    public void testFanout(){
        rabbitTemplate.convertAndSend("spring_fanout_exchange","","spring_fanout....");
    }


    /**
     * 发送topic类型消息
     */
    @Test
    public void testTopics(){
        rabbitTemplate.convertAndSend("spring_topic_exchange","old.orange.rabbit","spring_topic....");
    }
}

查看控制台

执行消费者监听test,依次执行简单模式、fanout类型、topic类型发送消息test。
在这里插入图片描述
一加载spring.xml文件就创建了如下队列及交换器。
在这里插入图片描述
在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/137125.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!