RabbitMQ消息监听(多种模式-fanout/topic)
博客专区 > ddyin 的博客 > 博客详情
RabbitMQ消息监听(多种模式-fanout/topic)
ddyin 发表于8个月前
RabbitMQ消息监听(多种模式-fanout/topic)
  • 发表于 8个月前
  • 阅读 0
  • 收藏 0
  • 点赞 0
  • 评论 0

移动开发云端新模式探索实践 >>>   

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

MQ消息配置监听:

package com.qf.openchannel.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 = ".mc.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 = ".mc.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.qf.openchannel.mq;

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

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

例如:退团消息的监听:

package com.qf.openchannel.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: 10.18.19.64
    port: 5674
    username: admin
    password: dangerous
    virtual-host: /msgbus
    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.当消费者消费信息出现异常时,比如消费者宕机,消息该如何处理,当生产者宕机时,消息该如何处理?

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

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

 

 

 

 

标签: RabbitMQ
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 1
博文 40
码字总数 60485
×
ddyin
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: