MQ笔记-MQ相关知识

本文介绍了如何在SpringBoot应用中集成和配置RabbitMQ,包括Docker部署、YML配置、手动配置ConnectionFactory、RabbitTemplate的设置以及消息确认机制。同时,文章详细展示了如何创建队列、交换机、死信队列、延迟队列和绑定,并提供了消费者和生产者的示例代码。
摘要由CSDN通过智能技术生成

一、RabbitMQ

    1:Docker 部署参考:docker 安装和使用_运行docker服务_Bonrui的博客-CSDN博客 中的docker-compose使用
    2:springboot整合RabbitMQ

# pom引入
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

# yml配置
spring:
  rabbitmq:
    port: 5672
    virtual-host: /hair
    host: 192.168.3.100
    username: hair
    password: hairadmin
    publisher-confirm-type: correlated #不管发送到交换机是否成功都回调
    publisher-returns: true #开启交换机到队列发送异常时回退模式
    listener:
      simple:
        acknowledge-mode: manual #消费者需要确认
        # prefetch: 1 消息预读数量
        retry:
          enabled: true
          max-attempts: 5 #最大重试次数
          max-interval: 60000 #最大间隔时间
          initial-interval: 1000ms #重试间隔
          multiplier: 2 #间隔因子 2 4 8 16
      direct:
        acknowledge-mode: manual #消费者需要确认
        # prefetch: 1 消息预读数量
        retry:
          enabled: true
          max-attempts: 5 #最大重试次数
          max-interval: 60000 #最大间隔时间
          initial-interval: 1000ms #重试间隔
          multiplier: 2 #间隔因子 2 4 8 16
# 除了使用yml配置文件自动装配外还可以手动注入Bean来配置,一般需要特殊配置时使用手动注入
    /**
     * 手动创建工厂连接 覆盖配置文件自动配置
     *
     * @return
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(rabbitMQProperties.getHost());
        connectionFactory.setVirtualHost(rabbitMQProperties.getVirtualHost());
        connectionFactory.setPort(rabbitMQProperties.getPort());
        connectionFactory.setUsername(rabbitMQProperties.getUsername());
        connectionFactory.setPassword(rabbitMQProperties.getPassword());
        connectionFactory.setPublisherReturns(rabbitMQProperties.getPublisherReturns());
        if (StrUtil.isBlank(rabbitMQProperties.getPublisherConfirmType())
                || CachingConnectionFactory.ConfirmType.CORRELATED.name().equals(rabbitMQProperties.getPublisherConfirmType().toUpperCase())) {
            connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
        }
        if (CachingConnectionFactory.ConfirmType.SIMPLE.name().equals(rabbitMQProperties.getPublisherConfirmType().toUpperCase())) {
            connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.SIMPLE);
        }
        if (CachingConnectionFactory.ConfirmType.NONE.name().equals(rabbitMQProperties.getPublisherConfirmType().toUpperCase())) {
            connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.NONE);
        }
        return connectionFactory;
    }

    @Bean
    public SimpleRabbitListenerContainerFactory myRabbitListenerContainerFactory() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory());
        factory.setMaxConcurrentConsumers(5);
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }
    /**
     * rabbitmq的模板配置
     *
     * @return
     */
    @Bean
    public RabbitTemplate rabbitTemplate() {
        rabbitTemplate = new RabbitTemplate(connectionFactory());
        // 发送到交换机:消息确认
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            log.info("RabbitMQ-发送到交换机:::Confirm callback id:{},ack:{},cause:{}", correlationData, ack, cause);
            if (ack) {
                log.info("RabbitMQ-发送到交换机:::成功");
            } else {
                log.info("RabbitMQ-发送到交换机:::失败-{}", cause);
            }
        });
        // 交换机到队列:这个参数为true表示如果发送消息到了RabbitMq,没有对应该消息的队列。那么会将消息返回给生产者,此时仍然会发送ack确认消息,否则丢弃消息
        rabbitTemplate.setMandatory(true);
        // 交换机到队列:Mandatory为true时设置broker消息返回
        rabbitTemplate.setReturnsCallback((returnedMessage) -> {
            log.info("RabbitMQ-交换机到队列退回:::return callback message:{},code:{},text:{},exchange:{},routingKey:{}",
                    returnedMessage.getMessage(), returnedMessage.getReplyCode(), returnedMessage.getReplyText(),
                    returnedMessage.getExchange(), returnedMessage.getRoutingKey());
        });
//        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey)
//                -> log.info("return callback message:{},code:{},text:{}", message, replyCode, replyText));
    }
#使用yml自动配置时 配置rabbitmq的模板
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @PostConstruct
    public void init() {
        // 发送到交换机:消息确认
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            log.info("RabbitMQ-发送到交换机:::Confirm callback id:{},ack:{},cause:{}", correlationData, ack, cause);
            if (ack) {
                log.info("RabbitMQ-发送到交换机:::成功");
            } else {
                log.info("RabbitMQ-发送到交换机:::失败-{}", cause);
            }
        });
        // 交换机到队列:这个参数为true表示如果发送消息到了RabbitMq,没有对应该消息的队列。那么会将消息返回给生产者,此时仍然会发送ack确认消息,否则丢弃消息
        rabbitTemplate.setMandatory(true);
        // 交换机到队列:Mandatory为true时设置broker消息返回
        rabbitTemplate.setReturnsCallback((returnedMessage) -> {
            log.info("RabbitMQ-交换机到队列退回:::return callback message:{},code:{},text:{},exchange:{},routingKey:{}",
                    returnedMessage.getMessage(), returnedMessage.getReplyCode(), returnedMessage.getReplyText(),
                    returnedMessage.getExchange(), returnedMessage.getRoutingKey());
        });
//        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey)
//                -> log.info("return callback message:{},code:{},text:{}", message, replyCode, replyText));
    }

     创建队列绑定交换机

#配置文件方式
    // 创建死信队列
    @Bean
    public Queue createDeadQueue() {
        return new Queue(MqConstants.DEADQUEUE, true);
    }
    // 创建死信交换机
    @Bean
    public DirectExchange createDeadExchange() {
        return new DirectExchange(MqConstants.DEADEXCHAGENAME, true, false);
    }
    // 死信交换机 死信队列 绑定
    @Bean
    public Binding createDeadBinding() {
        return BindingBuilder.bind(createDeadQueue()).to(createDeadExchange()).with(MqConstants.DEADQUEUE);
    }
    // 声明direct类型的Exchange
    @Bean
    public Exchange directExchange() {
        return new DirectExchange(MqConstants.EXCHAGENAME, true, false);
    }
    // 声明和direct类型的Exchange绑定的queue
    @Bean
    public List<Queue> queues() {
        List<Queue> queueList = new ArrayList<>();
        List<String> queueNames = Collections.singletonList(MqConstants.DEFAULTQUEUE);
        // 设置死信队列
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("x-dead-letter-exchange", MqConstants.DEADEXCHAGENAME);
        map.put("x-dead-letter-routing-key", MqConstants.DEADQUEUE);
        for (String queueName : queueNames) {
            queueList.add(new Queue(queueName, true, false, false, map));
        }
        return queueList;
    }
    // direct类型的Exchange绑定queue
    @Bean
    public List<Binding> bindings() {
        List<Binding> bindingList = new ArrayList<>();
        for (Queue queue : queues()) {
            bindingList.add(BindingBuilder.bind(queue).
                    to(directExchange()).with(queue.getName()).noargs());
        }
        return bindingList;
    }
    // 声明延迟交换机使用自定义的交换机CustomExchange,需要Mq安装rabbitmq-delayed-message-exchange插件参考开头安装环境
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> args = new HashMap<>(1);
        // 这里使用直连方式的路由,如果想使用不同的路由行为,可以修改,如 topic
        args.put("x-delayed-type", "direct");
        return new CustomExchange(MqConstants.DELAYEXCHAGENAME, "x-delayed-message", true, false, args);
    }
    // 声明和延时类型的Exchange绑定的queue
    @Bean
    public List<Queue> delayQueues() {
        List<Queue> queueList = new ArrayList<>();
        List<String> queueNames = Collections.singletonList(MqConstants.ORDERTIMEOUTQUEUE);
        // 设置死信队列
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("x-dead-letter-exchange", MqConstants.DEADEXCHAGENAME);
        map.put("x-dead-letter-routing-key", MqConstants.DEADQUEUE);
        for (String queueName : queueNames) {
            queueList.add(new Queue(queueName, true, false, false, map));
        }
        return queueList;
    }
    // 延时类型的Exchange绑定queue
    @Bean
    public List<Binding> delayBindings() {
        List<Binding> bindingList = new ArrayList<>();
        for (Queue queue : delayQueues()) {
            bindingList.add(BindingBuilder.bind(queue).
                    to(delayExchange()).with(queue.getName()).noargs());
        }
        return bindingList;
    }
    /**
     * 声明Topic交换机 用于广播消息如果本项目不消费可以不创建队列和绑定
     *
     * @return
     */
    @Bean
    public TopicExchange runtimeTopicexchange() {
        return new TopicExchange(MqConstants.RUNTIMETOPICEXCHAGENAME, true, false);
    }
    # 配置文件方式声明的Exchange和queue一般会在有监听时(注解)才被创建到Mq,如果消费者和生产者不在一个项目那么消费者启动时无法订阅消息,如果想项目启动就创建可以使用rabbitAdmin,或者不使用配置文件方式使用声明式注解方式来创建消费者
    @Autowired
    RabbitAdmin rabbitAdmin;
    // 创建初始化RabbitAdmin对象
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        // 只有设置为 true,spring 才会加载 RabbitAdmin 这个类
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }
    // 创建交换机和对列 解决懒加载 启动时不自动创建队列和交换机问题
    @Bean
    public void createExchangeQueue() {
        rabbitAdmin.declareExchange(createDeadExchange());
        rabbitAdmin.declareQueue(createDeadQueue());
        rabbitAdmin.declareBinding(createDeadBinding());

        rabbitAdmin.declareExchange(directExchange());
        for (Queue item : queues()) {
            rabbitAdmin.declareQueue(item);
        }
        for (Queue item : delayQueues()) {
            rabbitAdmin.declareQueue(item);
        }

        for (Binding item : bindings()) {
            rabbitAdmin.declareBinding(item);
        }
        for (Binding item : delayBindings()) {
            rabbitAdmin.declareBinding(item);
        }
        rabbitAdmin.declareExchange(runtimeTopicexchange());
    }
# 声明式注解方式
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "test",durable = "true", declare = "true", arguments = {}),
            exchange = @Exchange(value = "testEx", type = ExchangeTypes.TOPIC),
            key = {"aa"}
    ))
    public void aa(String msg) {
        System.out.println(msg);
    }
# 如果配置了重试可以配置最大重试次数结束时的监听
    /**
     * spring-retry重试机制:当重试次数达到最大,消息仍然消费失败时回调。
     * 如果开启这个类,则死信队列失效,消息消费失败,即使配置了死信队列,消息也不会进入死信队列。
     * 重试失败回调和死信队列只能二选一!!!spring 提供回调实现类有如下几个:
     * RejectAndDontRequeueRecoverer :消费失败,并且消息不再入列,spring默认使用。
     * ImmediateRequeueMessageRecoverer :将消息重新入列
     * RepublishMessageRecoverer:转发消息到指定的队列,
     *
     * @return
     */
    @Bean
    public MessageRecoverer messageRecoverer() {
        return (message, cause) -> {
            log.info("MQ调用spring-retry重试次数达到最大仍然失败-{}", message.toString());
        };
    }

    创建消费者

# 创建一个接口后面多个消费者可以有不同的实现
    public interface MqOrderDataProcessService<T> {
        // 数据业务处理
        void process(String str, Channel channel, Message message);
    }
    @Override
    @RabbitListener(queues = MqConstants.DEADQUEUE)
    public void process(String str, Channel channel, Message message) {
        try {
            log.info("MqDeadDataProcessService process recive data {}", str);
            // 确认消息消费成功,第二个参数multiple是否使用批量确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                // 消费者处理出了问题,需要告诉队列信息费失败重回队列,第二个参数multiple是否使用批量确认
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                // 还可以使用basicReject(拒绝一条消息),basicNack(拒绝多条消息),requeue参数为false时从队列删除或打入死信(打入死信需配置绑定了死信队列)为true时重回队列(需要谨慎设计程序的逻辑,否则很有可能导致消息一直重复消费失败并且重复重新入队,表现为消费者线程出现死循环逻辑,耗尽服务器CPU资源)
                // channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ex) {
                log.info("MqDeadDataProcessService process faild {}", ex.getMessage());
            }
            // 死信和重试只能有一个,重试次数最后回调messageRecoverer,上面try catch去掉直接抛异常就可以走重试
            // throw new BusinessException(e.getMessage());
        }
    }

    生产者发送消息

// 延时消息
rabbitTemplate.convertAndSend(MqConstants.DELAYEXCHAGENAME, MqConstants.ORDERTIMEOUTQUEUE, "55", message -> {
            message.getMessageProperties().setDelay(20000);
            return message;
        });
// 普通消息
rabbitTemplate.convertAndSend(MqConstants.EXCHAGENAME, MqConstants.DEFAULTQUEUE, "55");

    设置超时

// 方式一、通过队列属性设置,队列中所有消息都有相同的过期时间
@Bean
public Queue msgQueue() {
    // 设置队列消息过期时间
    Map<String, Object> arguments = new HashMap<>();
    arguments.put("x-message-ttl", 5000); // 单位毫秒
    return new Queue(msgQueue, true, false, false, arguments);
}
// 方式二、对消息本身进行单独设置,每条消息的TTL可以不同
this.rabbitTemplate.convertAndSend(exchange, routingKey, content, message -> {
    // 设置这条消息的过期时间
    message.getMessageProperties().setExpiration("5000");
    return message;
});
// 如果两种方式一起使用,则消息的TTL以两者之间较小的那个数值为准
// 消息在队列中的生存时间一旦超过设置的TTL值时,就会变成死信(Dead Message),消费者将无法再收到该消息。(如果队列设置了死信队列,那么这条消息就会被转发到死信队列上,后面可以正常消费)
// 方式一设置TTL的方式,消息一旦过期,就会从队列中抹去;第二种方式,即使消息过期,也不会马上从队列抹去,而是在消息被投递到消费者之前判定的。unacked中的消息不会立马过期,而是消费者重新启动后变为ready后过期,ready中的消息到期会自动过期

前台连接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值