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()