1.rabbitmq消息监听,兼容多种模式的消息,fanout/topic等模式java
MQ消息配置监听:spring
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以及二者的绑定关系。apache
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 keyapp
对于监听器,因为有多个监听,抽象出一个共同接口:ide
MQMessageAwareui
package com.test.ddyin.mq; public interface MQMessageAware { String getExchange(); void onMessage(String message); String getMQType(); String getRoutingKey(); }
而后对于不一样的监听可手动实现:this
例如:退团消息的监听:代理
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监听可实现不一样消息类型的监听。code
注意项目中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()