Spring整合RabbitMQ-配制文件方式-3-消息拉模式

拉消息的消费者

java 复制代码
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ConsumerGet {

    public static void main(String[] args) throws Exception {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-rabbit.xml");

        RabbitTemplate template = context.getBean(RabbitTemplate.class);


        Message receive = template.receive("queue.msg");

        //报文头中的消息编码
        String encoding = receive.getMessageProperties().getContentEncoding();

        System.out.println("收到的消息:" + new String(receive.getBody(), encoding));


        context.close();
    }
}

spring-rabbit.xml

java 复制代码
<?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: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/rabbit
    http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">

    <!--配制连接工厂-->
    <rabbit:connection-factory id="connectFactory"
                               host="node1" virtual-host="/"
                               username="root" password="123456"
                               port="5672"
    ></rabbit:connection-factory>


    <!--用于自动向RabbitMQ声明队列、交换器、绑定 等操作工具类-->
    <rabbit:admin id="rabbitAdmin" connection-factory="connectFactory"></rabbit:admin>


    <!--用于简化操作的模板类-->
    <rabbit:template connection-factory="connectFactory" id="rabbitTemplate"/>


    <!--声明队列队列-->
    <rabbit:queue id="msg1" name="queue.msg" durable="false" exclusive="false" auto-delete="false"></rabbit:queue>


</beans>

当启动消费者后,便可获取到发送至队列的消息

sh 复制代码
收到的消息:hello world

检查队列的消息的情况:

复制代码
[root@nullnull-os ~]# rabbitmqctl list_queues  --formatter pretty_table
Timeout: 60.0 seconds ...
Listing queues for vhost / ...
┌───────────┬──────────┐
│ name      │ messages │
├───────────┼──────────┤
│ queue.msg │ 0        │
└───────────┴──────────┘

经过检查确认,发现消息已经被消费了。

至此拉模式的消费者完成。

相关推荐
Flittly1 小时前
【AgentScope Java新手村系列】(17)长期记忆系统
java·spring boot·spring
从此以后自律3 小时前
Spring 全家桶
java·后端·spring
TanYYF4 小时前
spring ai入门教程一
java·人工智能·spring
AI人工智能+电脑小能手5 小时前
【大白话说Java面试题 第151题】【06_Spring篇】第11题:说一下 Spring Bean 的生命周期?
java·开发语言·后端·spring·面试
小明计算机毕业设计7 小时前
计算机毕业设计之基于SSM的汽车综合信息平台的设计与实现
java·spring·数据分析·汽车·课程设计·jsp
掘金小豆8 小时前
Spring 事务失效的 6 大场景,你踩过几个?
后端·spring·面试
咖啡八杯2 天前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
止语Lab2 天前
一次 goroutine 泄漏:pprof 说有 10 万个 goroutine,但问题不在 channel
rabbitmq
Flittly3 天前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
咖啡八杯4 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式