RabbitMQ消息监听(多种模式-fanout/topic)

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 messageListeners;

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

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

	@Bean
	List binding() {
		return messageListeners.stream().map(listener -> {
			return new Binding(listener.getExchange() + queueNameSufix, DestinationType.QUEUE, listener.getExchange(),
					listener.getRoutingKey(), new HashMap());
		}).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 {
	
	private final String queueNameSufix = ".test.channel";
	private ApplicationContext applicationContext;
	private Map 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 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()

 

 

 

 

转载于:https://my.oschina.net/u/3110937/blog/1535865

你可能感兴趣的:(RabbitMQ消息监听(多种模式-fanout/topic))