Springboot+Rabbit 保证消费顺序(单活队列,项目多实例部署只有一个消费)

Rabbit实现单活队列

为了保证消费顺序,需要只有一个实例进行按顺序消费,其他实例仅提供日常对外服务,不进行消息消费。当唯一消费实例无法消费或掉线时,会自动开启下一个消费者进行消费,保证多个实例消费者中仅有一个正常消费,其他作为备选。这时就会用到消费者单活模式

使用起来很简单,只是在声明队列的时候的参数 (arguments参数),将x-single-active-consumer设置为True即可。

申明方法1(Bean):

package com.cdn.mqprovider.config.single_active;

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cdn
 * @desc
 * @date 2023/03/26 21:23
 */
@Configuration
public class SingActiveConfig {
    
    

    /**
     * @author cdn
     * @desc   单活模式队列什么
     * 这时,为了保证消费顺序,需要只有一个实例进行按
     * 顺序消费,其他实例仅提供日常对外服务,不进行消
     * 息消费。当唯一消费实例无法消费或掉线时,会自动
     * 开启下一个消费者进行消费,保证多个实例消费者中
     * 仅有一个正常消费,其他作为备选。
     * @date 2023/03/26 21:21
     */
    @Bean
    public Queue singActive() {
    
    
        Map<String, Object> arguments = new HashMap<>(2);
        arguments.put("x-single-active-consumer", true);
        return new Queue("singActive", true, false, false, arguments);
    }
}

申明方法2(注解):

package com.cdn.mqprovider.listen;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author cdn
 * @desc  注解式自动创建队列和交换机
 * @date 2023/03/26 21:42
 */
@Slf4j
@Component
public class SingActiveListen {
    
    

    /**
     * 单活队列:  多实例下只会有一个消费(注解式申明)
     自动创建,queue 和 exchange 绑定
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "car",
                    arguments = {
    
    
                            @Argument(name = "x-single-active-consumer", value = "true", type = "java.lang.Boolean")
                    }),
            key = "carKey",
            exchange = @Exchange(value = "carExchange", type = "direct")
    ))
    public void car2(String msg){
    
    
        System.out.println("-------car--------" + msg);
    }
}

猜你喜欢

转载自blog.csdn.net/caidingnu/article/details/129786332
今日推荐