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        │
└───────────┴──────────┘

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

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

相关推荐
小张小张爱学习22 分钟前
Mybatis高频面试题
java·spring·mybatis
直奔標竿31 分钟前
Java开发者AI转型第十三课!知识库终局方案:Spring AI Vector Store架构演进与ETL全链路入库实战
java·人工智能·后端·spring
星轨zb43 分钟前
什么是Spring设计模式:单例、工厂与代理
java·spring·设计模式
.柒宇.1 小时前
SpringCloud微服务入门教程
spring·spring cloud·微服务
java1234_小锋1 小时前
RabbitMQ中有哪几种交换机类型?
分布式·rabbitmq
代码漫谈1 小时前
探索RabbitMQ集群:如何实现消息的高可用性和负载均衡
分布式·消息队列·rabbitmq·负载均衡
.生产的驴1 小时前
SpringBoot 大文件分片上传 文件切片、断点续传与性能优化 切片技术与优化方案 文件高效上传
java·服务器·spring boot·后端·spring·spring cloud·状态模式
练习时长一年14 小时前
Spring配置类的演化
java·spring boot·spring
invicinble14 小时前
Spring如何把bean注册到容器里
java·后端·spring