RabbitMQ确认,返回机制,异步发送配置类,(开箱即用)

有关MQ详情请看

RabbitMQ安装使用,六种工作模式,详解

pom文件引入

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

配置类

package com.aeotrade.gateway.mq;

import org.springframework.amqp.rabbit.AsyncRabbitTemplate;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

import static com.aeotrade.gateway.mq.RabbitMQTopic.DefaultExange;

@Component
public class RabbitSender {
    //自动注入RabbitTemplate模板类
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Autowired
    private AsyncRabbitTemplate asyncRabbitTemplate;

    //确认机制
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        /**
         * correlationData: 回调的相关数据,包含了消息ID
         * ack: ack结果,true代表ack,false代表nack
         * cause: 如果为nack,返回原因,否则为null
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.err.println("correlationData: " + correlationData);
            System.err.println("ack: " + ack);
            if(!ack){
                //做一些补偿机制等
                System.err.println("异常处理....");
            }
        }
    };
    //返回机制
    final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText,
                                    String exchange, String routingKey) {
            System.err.println("return exchange: " + exchange + ", routingKey: "
                    + routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
        }
    };

    //发送消息方法调用: 构建Message消息
    public void send(String topic, Object message, Map<String, Object> properties) throws Exception {
        MessageHeaders messageHeaders = new MessageHeaders(properties);
        //注意导包
        Message msg = MessageBuilder.createMessage(message, messageHeaders);
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        //id + 时间戳 ,保证全局唯一 ,这个是实际消息的ID
        //在做补偿性机制的时候通过ID来获取到这条消息进行重发
        String id = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(id);
        //exchange, routingKey, object, correlationData
        //rabbitTemplate.convertSendAndReceive(DefaultExange, topic,  msg, correlationData);

        asyncRabbitTemplate.convertSendAndReceive(DefaultExange, topic,  msg);
    }

    @Bean
    public AsyncRabbitTemplate asyncRabbitTemplate(RabbitTemplate rabbitTemplate) {
        AsyncRabbitTemplate asyncRabbitTemplate = new AsyncRabbitTemplate(rabbitTemplate);
        asyncRabbitTemplate.setReceiveTimeout(10000);

        return asyncRabbitTemplate;
    }



}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 和 RabbitMQ 结合使用可以方便地构建基于消息队列的异步通信系统。在 Spring Boot 中,RabbitMQ 提供了一个简单易用的整合方案,让你能够轻松地处理消息的生产者(Producer)和消费者(Consumer)。 1. 引入依赖:首先,你需要在你的 Maven 或 Gradle 项目中添加 Spring AMQP 和 RabbitMQ 的依赖。例如,Maven 项目的 pom.xml 文件中添加: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 2. 配置 RabbitMQ:在 application.properties 或 application.yml 文件中配置 RabbitMQ 的连接信息,包括主机名、端口号、队列名称等。 ```properties spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest ``` 3. 创建 RabbitMQ配置Spring Boot 会自动扫描该下的配置,比如创建 RabbitTemplate 实例。 ```java import org.springframework.amqp.core.AmqpAdmin; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitConfig { @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory factory = new CachingConnectionFactory(); factory.setHost("localhost"); factory.setUsername("guest"); factory.setPassword("guest"); return factory; } @Bean public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) { RabbitTemplate template = new RabbitTemplate(connectionFactory); return template; } } ``` 4. 生产者(发送消息):使用 `RabbitTemplate` 发送消息到指定队列。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class RabbitProducer { @Autowired private RabbitTemplate rabbitTemplate; public void sendMessage(String message, String queueName) { rabbitTemplate.convertAndSend(queueName, message); } } ``` 5. 消费者(接收消息):创建一个消费者,监听指定队列,并处理接收到的消息。 ```java import org.springframework.amqp.annotation.DeleteQueue; import org.springframework.amqp.annotation.QueueBind; import org.springframework.amqp.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component @QueueBind(value = "myQueue") public class RabbitConsumer { @RabbitListener public void receiveMessage(String message) { System.out.println("Received message: " + message); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值