当mq相关的功能只是项目的一部分独立功能,进行开发的时候可能不总是有mq的环境,这时如果使用jms,控制台就会一直输出mq连接失败的信息——如果可以控制mq连接的开启和关闭,就不会一直弹出连接失败了。这在spring boot里要怎么做?
想当初研究了一阵spring jms的源码,了解spring是如何通过一个注解来启动一个consumer,具体过程已经不记得了,指出要点
不使用JmsListener注解来注册消费者,自行注入MessageListenerContainer来控制consumer的启停
第一步,consumer的注册类
外部只需要调用injectConsumers方法及完成MessageListenerContainer的注册,每个consumer都在唯一的一个container中
@Component
@Slf4j
public class ConsumerRegister {
private static SimpleMessageConverter jmsConverter = new SimpleMessageConverter();
private ConfigurableApplicationContext applicationContext;
private ConnectionFactory connectionFactory;
public ConsumerRegister(ConfigurableApplicationContext applicationContext, ConnectionFactory connectionFactory) {
this.applicationContext = applicationContext;
this.connectionFactory = connectionFactory;
}
public Map<String, DefaultMessageListenerContainer> injectConsumers(Map<ActiveMQDestination, CustomConsumer> input) {
if (null == input || input.size() <= 0) {
return null;
}
Map<String, DefaultMessageListenerContainer> result = new HashMap<>();
Random rnd = new Random();
for (Map.Entry<ActiveMQDestination, CustomConsumer> destinationCustomConsumerEntry : input.entrySet()) {
ActiveMQDestination destination = destinationCustomConsumerEntry.getKey();
CustomConsumer consumer = destinationCustomConsumerEntry.getValue();
BeanDefinitionBuilder definitionBuilder = getListenerContainerBeanBuilder(destination, consumer);
String beanName = ("consumer_" + System.currentTimeMillis()) + "_" + rnd.nextInt(32);
registeListenerContainerBean(beanName, definitionBuilder);
res