Mq动态监听queue

RabbitAdmin spring的mq底层封装,由于各种declare操作比如declareQueue,declareExchange
SimpleMessageListenerContainer,spring的监听封装

创建mq动态添加类


@Slf4j
public class MqListener {

    public MqListener() {
        param.put("x-queue-type", "classic");
    }

    private String mqServiceName;
    private SimpleMessageListenerContainer container = null;
    private Map<String, Object> param = new HashMap<>();
    private RabbitAdmin rabbitAdmin = null;
    private IMqHandler mqHandler;

    public MqListener(ConnectionFactory connectionFactory, String mqServiceName,IMqHandler mqHandler) {
        this.mqServiceName = mqServiceName;
        this.mqHandler = mqHandler;
        this.rabbitAdmin = new RabbitAdmin(connectionFactory);
        rabbitAdmin.setAutoStartup(true);
        rabbitAdmin.afterPropertiesSet();
        container = new SimpleMessageListenerContainer();
        container.setAmqpAdmin(rabbitAdmin);
        container.setConcurrentConsumers(1);
        // 最大的并发消费者
        container.setMaxConcurrentConsumers(5);
        // 设置是否重回队列
        container.setDefaultRequeueRejected(false);
        // 设置签收模式
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        //设置消费者的Arguments
        Map<String, Object> args = new HashMap<>();
        args.put("type", "my-mq-listener");
        container.setConsumerArguments(args);
        container.setConsumerTagStrategy((queue) -> mqServiceName + "_queue_" + queue + "_" + UUID.randomUUID());
        // 设置非独占模式
        container.setExclusive(false);
        // 设置consumer未被 ack 的消息个数
        container.setPrefetchCount(1);
        container.setMessageListener((ChannelAwareMessageListener) (message, channel) -> {
            try {
                this.mqHandler.todo(this.mqServiceName, message);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (Exception e) {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        });
        container.setConnectionFactory(connectionFactory);
        container.afterPropertiesSet();
    }

    /**
     * 需要监听的queueNames
     *
     * @param queueNames
     */
    public SimpleMessageListenerContainer addListenerQueue(String... queueNames) {
        this.container.addQueueNames(queueNames);
        return this.container;
    }

    /**
     * 再服务端声明 关系
     *
     * @param queueName
     * @param routeKey
     * @param exchange
     * @param exchangeType
     */
    public void declareQueue(String queueName, String routeKey, String exchange, String exchangeType) {
        if (StringUtils.isEmpty(routeKey)) {
            log.warn("add routeKey is null");
            return;
        }
        if (topic.equals(exchangeType)) {
            TopicExchange ex = new TopicExchange(exchange, true, false);
            Queue queue = new Queue(queueName, true, false, false, param);
            this.rabbitAdmin.declareExchange(ex);
            this.rabbitAdmin.declareQueue(queue);
            Binding binding = BindingBuilder.bind(queue).to(ex).with(routeKey);
            this.rabbitAdmin.declareBinding(binding);
        } else {
            throw new RuntimeException("not support " + exchangeType);
        }
    }

    public int removeQueueNames(String... queueNames) {
        this.container.removeQueueNames(queueNames);
        return this.container.getQueueNames().length;
    }

    public void removeBind(String queueName, String routeKey, String exchange, String exchangeType) {
        if (StringUtils.isEmpty(routeKey)) {
            log.warn("add routeKey is null");
            return;
        }
        if ("topic".equals(exchangeType)) {
            TopicExchange ex = new TopicExchange(exchange, true, false);
            Queue queue = new Queue(queueName, true, false, false, param);
            Binding binding = BindingBuilder.bind(queue).to(ex).with(routeKey);
            this.rabbitAdmin.removeBinding(binding);
        } else {
            //其他类型自己添加
            throw new RuntimeException("not support " + exchangeType);
        }
    }


    public void start() {
        if (container.isRunning()) {
            return;
        }
        this.container.start();
    }

    public String printInfo() {
        StringBuilder sb = new StringBuilder(this.mqServiceName);
        sb.append(" is ").append(this.container.isRunning() == true ? "Running" : "Stopped")
                .append(" queues is ").append(JsonUtil.to(this.container.getQueueNames()));
        return sb.toString();
    }


    public void stop() {
        this.container.stop();
    }

}

使用上面的类如下
1、先根据自己的环境创建connection

@Component
@Data
@ConfigurationProperties(prefix = "my.mq")
public class MqProperties {

    private List<MqYml> mqYmlList;

    @Data
    public static class MqYml {
        private String addresses;
        private int port;
        private String username;
        private String password;
        private String virtualHost;
        private String mqServiceName;
    }
}
private Map<String, ConnectionFactory> getMqConnection() {
    Map<String, ConnectionFactory> returns = Maps.newConcurrentMap();
    for (MqProperties.MqYml mqYml : mqProperties.getMqYmlList()) {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(mqYml.getAddresses());
        connectionFactory.setPort(mqYml.getPort());
        connectionFactory.setUsername(mqYml.getUsername());
        connectionFactory.setPassword(mqYml.getPassword());
        connectionFactory.setVirtualHost(mqYml.getVirtualHost());
        connectionFactory.afterPropertiesSet();
        returns.put(mqYml.getMqServiceName(), connectionFactory);
    }
    return returns;
}

2、根据自己需求创建自己服务监听
这里mqServiceName对应的是一个mqserver 可以是不通ip或者不用vhost

//mqHisHandler 自己实现了todo的监听接口
MqListener mqListener = new MqListener(connectionFactory, "serviceAname", mqHisHandler);
//开启声明,routingkey和queue和exchange的关系
mqListener.declareQueue("QueueName", "RouteKey"
        , "ExchangeName", "ExchangeType");
//监听列队        
addListenerQueue("QueueName1","QueueName2").start()
//动态删除列队
mqListener.stop();
//forListenerQueueNames 返回的是该监听器里面还有多少被监听的queue
int forListenerQueueNames = mqListener.removeQueueNames(lmRecordHis.getQueueName());
//如果此监听器没有监听的列队了,就不需要start了
if (forListenerQueueNames != 0) {
    mqListener.start();
}

handler的实现

@Override
public void todo(String mqServiceName, Message message) {
    try {
        String routeKey = message.getMessageProperties().getReceivedRoutingKey();
        String exchange = message.getMessageProperties().getReceivedExchange();
        String queueName = message.getMessageProperties().getConsumerQueue();
        //这里需要判断routeKey 是否是自己需要的
        //为什么需要判断请看我上一个文章
        
    } catch (Exception e) {
        log.error("save message error ", e);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值