在Spring应用程序启动时,我想在Redis
中查找一个值,根据该值,我想关闭或保留我拥有的消息侦听器。
也有可能根本不初始化这些bean,但我也找不到任何一种方法。
此刻,我正在尝试使用Spring的ApplicationReadyEvent
关闭容器。
@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent> {
private @Autowired @Qualifier("completedOrderContainer") SimpleMessageListenerContainer container;
private @Autowired RedisManagerImpl redis;
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
if (!Boolean.valueOf(redis.isRabbitListenerActive())) container.shutdown();
}
}
容器和AMQP Bean初始化为:
@Bean
@Conditional(RabbitCondition.class)
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setAddresses(rabbitHost + ":" + rabbitPort);
connectionFactory.setUsername(rabbitUsername);
connectionFactory.setPassword(rabbitPassword);
return connectionFactory;
}
@Bean
@Conditional(RabbitCondition.class)
Queue completedOrderQueue() {
return new Queue(completedOrderQueueName, true);
}
@Bean
@Conditional(RabbitCondition.class)
TopicExchange completedOrderExchange() {
return new TopicExchange(completedOrderExchangeName);
}
@Bean
@Conditional(RabbitCondition.class)
Binding binding(Queue completedOrderQueue, TopicExchange completedOrderExchange) {
return BindingBuilder.bind(completedOrderQueue).to(completedOrderExchange).with(completedOrderQueueName);
}
@Bean
@Conditional(RabbitCondition.class)
SimpleMessageListenerContainer completedOrderContainer(ConnectionFactory connectionFactory, MessageListenerAdapter completedOrderListenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(completedOrderQueueName);
container.setMessageListener(completedOrderListenerAdapter);
return container;
}
@Bean
@Conditional(RabbitCondition.class)
MessageListenerAdapter completedOrderListenerAdapter(CompletedOrderMessageReceiver receiver) {
return new MessageListenerAdapter(receiver, "completedOrder");
}
消息侦听器:
@Component
public class CompletedOrderMessageReceiver {
public void completedOrder(Object asyncTask) throws Exception {
//impl
}
}
问题是,如果我在队列中已有消息的情况下启动应用程序,则消息侦听器将在执行container.shutdown()
之前拾取消息。
有没有办法实现我的目标?即使采用不同的方法
在侦听器容器上将autoStartup
设置为false
。然后根据需要start()
和stop()
。