RabbitMQ Spring(三)RabbitTemplate

本文详细介绍了如何在Spring框架下配置RabbitMQ,包括创建连接工厂、交换机、队列及绑定,并展示了如何使用RabbitTemplate进行消息的发送与自定义消息属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RabbitMQ 配置

package com.bfxy.spring;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan({"com.bfxy.spring.*"})
public class RabbitMQConfig {

    public final static String HOST = "127.0.0.1";

    @Bean
    public ConnectionFactory connectionFactory(){
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(HOST);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        return connectionFactory;
    }

    @Bean
    public TopicExchange exchange001() {
        return new TopicExchange("topic001", true, false);
    }

    @Bean
    public Queue queue001() {
        return new Queue("queue001", true); //队列持久
    }

    @Bean
    public Binding binding001() {
        return BindingBuilder.bind(queue001()).to(exchange001()).with("spring.*");
    }

    @Bean
    public TopicExchange exchange002() {
        return new TopicExchange("topic002", true, false);
    }

    @Bean
    public Queue queue002() {
        return new Queue("queue002", true); //队列持久
    }

    @Bean
    public Binding binding002() {
        return BindingBuilder.bind(queue002()).to(exchange002()).with("rabbit.*");
    }

    @Bean
    public Queue queue003() {
        return new Queue("queue003", true); //队列持久
    }

    @Bean
    public Binding binding003() {
        return BindingBuilder.bind(queue003()).to(exchange001()).with("mq.*");
    }

    @Bean
    public Queue queue_image() {
        return new Queue("image_queue", true); //队列持久
    }

    @Bean
    public Queue queue_pdf() {
        return new Queue("pdf_queue", true); //队列持久
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        return rabbitTemplate;
    }
    
}

RabbitTemplate 使用

package com.bfxy.spring;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSendMessage() throws Exception {

        MessageProperties messageProperties = new MessageProperties();
        messageProperties.getHeaders().put("desc", "信息描述..");
        messageProperties.getHeaders().put("type", "自定义消息类型..");
        Message message = new Message("Hello RabbitMQ".getBytes(), messageProperties);

        rabbitTemplate.convertAndSend("topic001", "spring.amqp", message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                System.err.println("------添加额外的设置---------");
                message.getMessageProperties().getHeaders().put("desc", "额外修改的信息描述");
                message.getMessageProperties().getHeaders().put("attr", "额外新加的属性");
                return message;
            }
        });

    }

    @Test
    public void testSendMessage2() throws Exception {

        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setContentType("text/plain");
        Message message = new Message("mq 消息1234".getBytes(), messageProperties);

        rabbitTemplate.send("topic001", "spring.abc", message);

        rabbitTemplate.convertAndSend("topic001", "spring.amqp", "hello object message send!");
        rabbitTemplate.convertAndSend("topic002", "rabbit.abc", "hello object message send!");

    }
    
}
### 集成 RabbitMQSpring Cloud 的方法 在 Spring Cloud 中集成 RabbitMQ 是一种常见的需求,用于实现消息队列通信和分布式系统的解耦。以下是关于如何配置、使用以及提供示例代码的详细介绍。 #### 1. 添加依赖项 为了在项目中启用 RabbitMQ 支持,需要引入 `spring-boot-starter-amqp` 和其他必要的依赖项。这些依赖可以通过 Maven 或 Gradle 进行管理: 对于 Maven 用户: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 对于 Gradle 用户: ```gradle implementation 'org.springframework.boot:spring-boot-starter-amqp' ``` 此操作会自动导入所需的 RabbitMQ 客户端库和其他支持组件[^2]。 --- #### 2. 配置 RabbitMQ 参数 通过 `application.properties` 文件可以轻松设置 RabbitMQ 的连接参数。以下是一个典型的配置示例: ```properties spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest ``` 如果使用的是 Docker 环境或其他主机地址,则需调整对应的 `host` 值以匹配实际部署环境[^4]。 --- #### 3. 创建生产者类 创建一个简单的生产者来发送消息到指定的消息队列。下面展示了一个基于注解的方式定义 RabbitTemplate 并向队列推送数据的例子: ```java import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MessageProducer { @Autowired private RabbitTemplate rabbitTemplate; public void sendMessage(String message) { rabbitTemplate.convertAndSend("myQueue", message); System.out.println("Message sent: " + message); } } ``` 在此处,“myQueue”代表目标队列名称,可以根据具体业务逻辑自定义命名规则[^1]。 --- #### 4. 实现消费者功能 同样地,利用监听器模式接收来自特定队列中的消息。这里给出一段基本代码片段作为参考: ```java import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class MessageConsumer { @RabbitListener(queues = "myQueue") public void receiveMessage(String message) { System.out.println("Received message: " + message); } } ``` 当有新消息到达 “myQueue” 时,该方法会被触发并打印接收到的内容至控制台[^3]。 --- #### 5. 测试整体流程 启动应用程序之后,调用 `sendMessage()` 方法即可验证整个链路是否正常工作。例如,在控制器层面上设计接口供外部访问测试用途: ```java @RestController @RequestMapping("/api/messages") public class MessageController { @Autowired private MessageProducer producer; @PostMapping public ResponseEntity<String> send(@RequestBody String content){ producer.sendMessage(content); return ResponseEntity.ok("Message Sent"); } } ``` 以上即完成了从初始化到运行的一个完整周期演示过程。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值