RabbitMQ消息监听(多种模式

Stella981
• 阅读 872

1.rabbitmq消息监听,兼容多种模式的消息,fanout/topic等模式

MQ消息配置监听:

package com.test.ddyin.conf;

import java.util.HashMap;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.apache.poi.ss.formula.functions.T;
import org.springframework.amqp.core.AbstractExchange;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Binding.DestinationType;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.qf.openchannel.mq.MQMessageAware;
import com.qf.openchannel.mq.MQReceiver;

@Configuration
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "enable", matchIfMissing = false)
public class MQInitConfig {

    private final String queueNameSufix = ".test.channel";
    @Autowired
    private List<MQMessageAware> messageListeners;

    @Bean
    List<Queue> queue() {
        return messageListeners.stream().map(listener -> {
            return new Queue(listener.getExchange() + queueNameSufix, false);
        }).collect(Collectors.toList());
    }

    @Bean
    List<Exchange> exchange() {
        return messageListeners.stream().map(listener -> {
            return new AbstractExchange(listener.getExchange()) {
                @Override
                public String getType() {
                    return listener.getMQType();
                }
            };
        }).collect(Collectors.toList());
    }

    @Bean
    List<Binding> binding() {
        return messageListeners.stream().map(listener -> {
            return new Binding(listener.getExchange() + queueNameSufix, DestinationType.QUEUE, listener.getExchange(),
                    listener.getRoutingKey(), new HashMap<String, Object>());
        }).collect(Collectors.toList());
    }

    @Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
            MessageListenerAdapter listenerAdapter) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setMessageListener(listenerAdapter);
        messageListeners.forEach(listener -> {
            container.addQueueNames(listener.getExchange() + queueNameSufix);
        });
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(MQReceiver receiver) {
        return new MessageListenerAdapter(receiver);
    }
}

注意:在绑定的时候,要加入exchange和routing key(fanout模式的routing key 为空字符串),其中,在queue,exchange和binding加注解,相当于是在容器中添加了exchange,队列和两者之间的绑定关系,可以直接从applicationContext中获取,其中,也是自动创建了exchange,queue以及两者之间的绑定关系,不需要在rabbitmq界面重新添加exchange,queue以及两者的绑定关系。

MQ消息接收:(MQReceiver)

package com.qf.openchannel.mq;

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

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import com.qf.openchannel.util.Constant;
import com.qf.openchannel.util.LoggerUtil;

@Service
public class MQReceiver implements MessageListener, ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {
    
    private final String queueNameSufix = ".test.channel";
    private ApplicationContext applicationContext;
    private Map<String, MQMessageAware> messageListener = new HashMap<>();

    @Override
    public void onMessage(Message message) {
        String payload = new String(message.getBody());
        LoggerUtil.info("Received <" + payload + ">");
        try {            
            String exchange = message.getMessageProperties().getConsumerQueue();
            String routingKey = message.getMessageProperties().getReceivedRoutingKey();
            LoggerUtil.info("MQReceiverService onMessage routingKey {} exchange {}", routingKey,exchange);
            if (messageListener.containsKey(exchange)) {
                if(messageListener.containsKey(routingKey)) {
                    messageListener.get(routingKey).onMessage(payload);
                }else {
                    messageListener.get(exchange).onMessage(payload);
                }
            } else {
                LoggerUtil.info("MQReceiverService receiveMessage unrecognized message from exchange : ", exchange);
            }
        } catch (Exception e) {
            LoggerUtil.error("MQReceiverService receiveMessage exception: ", e);
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        applicationContext.getBeansOfType(MQMessageAware.class).forEach((key, listener) -> {
            if(listener.getMQType().equals(Constant.MQTYPE_TOPIC)) {
                LoggerUtil.info("MQReceiverService receiveMessage messageType {} routingKey {} exchange {}", listener.getMQType(), listener.getRoutingKey(),listener.getExchange());
                messageListener.put(listener.getExchange() + queueNameSufix, listener);
                messageListener.put(listener.getRoutingKey(), listener);
            }else if(listener.getMQType().equals(Constant.MQTYPE_FANOUT)){
                LoggerUtil.info("MQReceiverService receiveMessage messageType {} routingKey {} exchange {}", listener.getMQType(), listener.getRoutingKey(),listener.getExchange());
                messageListener.put(listener.getExchange() + queueNameSufix, listener);
            }else {
                
            }
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

注意:区分不同消息类型来绑定不同的监听,对于topic模式,routing key也要绑定对应的listener(监听器),然后通过message可获取监听的exchange和routing key

对于监听器,由于有多个监听,抽象出一个共同接口:

MQMessageAware

package com.test.ddyin.mq;

public interface MQMessageAware {
    String getExchange();
    void onMessage(String message);
    String getMQType();
    String getRoutingKey();
}

然后对于不同的监听可手动实现:

例如:退团消息的监听:

package com.test.ddyin.mq;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.openchannel.model.QuitPlan;
import com.qf.openchannel.service.QuitPlanService;
import com.qf.openchannel.util.Constant;
import com.qf.openchannel.util.DateUtil;
import com.qf.openchannel.util.LoggerUtil;

/**
 * @author ddyin
 * @date 2017年9月8日 下午14:08:34
 */
@Service
public class QuitPlanListener implements MQMessageAware{
    
    @Autowired
    QuitPlanService quitPlanService;

    @Override
    public String getExchange() {
        return "trade.topic.notification";
    }

    @Override
    public void onMessage(String message) {
        try {
            LoggerUtil.info("QuitPlanListener dealMessage start: {}", DateUtil.get14Date());
            ObjectMapper mapper = new ObjectMapper();
            QuitPlan quitPlan = mapper.readValue(message, QuitPlan.class);
            quitPlanService.insertQuitPlan(quitPlan);
            LoggerUtil.info("QuitPlanListener dealMessage end: {}", DateUtil.get14Date());
        } catch (Exception e) {
            LoggerUtil.error("QuitPlanListener.onMessage Exception:{}", e);
        }
    }

    @Override
    public String getMQType() {
        return Constant.MQTYPE_TOPIC;
    }
    
    @Override
    public String getRoutingKey() {
        return "trade.plan.status.settled";
    }
    
}

到此,rabbitmq监听可实现不同消息类型的监听。

注意项目中rabbitmq的配置:

rabbitmq:
    host: 6.6.6.6
    port: 5674
    username: test
    password: test
    virtual-host: /test
    enable: false

综述,end

补充:

如果想扩展到多个virtualHost,可以添加ConnectionFactory

其中配置的virtualHost配置在配置文件中,目的是区分对接不同的业务,通过virtualHost来进行隔离。

事例如下:(放置在MqInitConfig.java文件中)

    /**
     * virtual-host: /host1 ConnectionFactory
     *
     * @return
     */
    @Bean
    ConnectionFactory connectionFactory1() {
        com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
        connectionFactory.setHost(mqConfig.getHost());
        connectionFactory.setPort(mqConfig.getPort());
        connectionFactory.setUsername(mqConfig.getUsername());
        connectionFactory.setPassword(mqConfig.getPassword());
        connectionFactory.setVirtualHost(mqConfig.getVirtualHost1());

        CachingConnectionFactory factory = new CachingConnectionFactory(connectionFactory);
        return factory;
    }

    /**
     * virtual-host: /host2 ConnectionFactory
     *
     * @return
     */
    @Bean
    ConnectionFactory connectionFactory2() throws IOException, TimeoutException {
        com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
        connectionFactory.setHost(mqConfig.getHost());
        connectionFactory.setPort(mqConfig.getPort());
        connectionFactory.setUsername(mqConfig.getUsername());
        connectionFactory.setPassword(mqConfig.getPassword());
        connectionFactory.setVirtualHost(mqConfig.getVirtualHost2());


        CachingConnectionFactory factory = new CachingConnectionFactory(connectionFactory);
        return factory;
    }

添加完之后将多个virtualHost加入到SimpleRoutingConnectionFactory

@Bean
    ConnectionFactory connectionFactory() {
        SimpleRoutingConnectionFactory factory = new SimpleRoutingConnectionFactory();
        Map<Object, ConnectionFactory> targetConnectionFactories = new HashMap<>();
        targetConnectionFactories.put("connectionFactory1", connectionFactory1());
        try {
            targetConnectionFactories.put("connectionFactory2", connectionFactory2());
        } catch (IOException e) {
            LoggerUtil.error("connectionFactory targetConnectionFactories IOException: {}", e);
        } catch (TimeoutException e) {
            LoggerUtil.error("connectionFactory targetConnectionFactories TimeoutException: {}", e);
        }
        factory.setTargetConnectionFactories(targetConnectionFactories);
        return factory;
    }

可以将对应的connectionFactory添加到container中,通过virtualHost来进行区分。

    @Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
                                              MessageListenerAdapter listenerAdapter) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setMessageListener(listenerAdapter);
        messageListeners.forEach(listener -> {
            if (MQ_RABBIT_VIRTUAL_HOST2.equals(listener.getVirtualHost())) {
                container.addQueueNames(listener.getExchange() + queueNameSufix);
            }else{
                //container.addQueueNames(listener.getExchange() + queueNameSufix);
                //或者其他业务逻辑
            }
        });
        return container;
    }

当然也要在MQMessageAware接口中添加方法:

public interface MQMessageAware {
    String getExchange();
    void onMessage(String message);
    String getMQType();
    String getRoutingKey();
    String getVirtualHost();
}

可实现多种virtualHost多种配置。。。

补充:

1.当消费者消费信息出现异常时,比如消费者宕机,消息该如何处理,当生产者宕机时,消息该如何处理?

A:对于消费者宕机,rabbitmq提供ack机制,当ack机制设置成true的时候,说明是生产者已经接收到消费者已经完全消费了信息,就会删除掉已经消费掉的信息。

    对于生产者宕机,rabbitmq提供了持久化机制,这里的持久化包含了exchange,queue,message的持久化,MessageDeliveryMode的deliveryMode可设置是否持久化,新建exchange和queue的时候也可设置,持久化属性是durable。

2.如何确认消息是否已发送到broker代理服务器上(broker其实就是一个消息队列的服务器实体,包含exchange,queue和binding的信息)

A:方式一:消息队列的channel的confirm模式是针对消息还未到达broker服务器做的一个弥补机制,channel设置成confirm模式后,就可以在到达broker服务器时发送一个反馈(每个消息在发送到broker服务器时都有一个唯一ID)

    方式二:消息队列是基于AMQP协议的,通过AMQP协议的事务机制来实现,是基于AMQP协议层面的解决方案。其实就是Channel中的txSelect(),txCommit()和txRollBack()

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
00_设计模式之语言选择
设计模式之语言选择设计模式简介背景设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总结。设计模式(Designpattern)代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这