前段时间在项目中用到rabbitmq来进行开门红期间的流量削峰,当我们把发送消息和接收消息的代码写好后,发现了一个问题:
在后台逻辑处理过程中需要使用到Redis,但是从bean容器中获取Redis的类的时候会出现取不到的问题。。。后来我在Redis的类和监听类里面分别加上了日志输出来观察谁先被加载,结果发现不管怎样都是监听类先启动的,而后Redis类才被加载。
这个问题让我很是头疼,后来在网上搜到了关于ApplicationListener这个接口。
ApplicationListener是spring提供的接口,作用是在web服务器启动时去加载某些程序。
随后我用了下面的方法实现了在加载完applicationContext.xml配置中的所有bean后再来加载消息队列的
监听类。
@Component
public class StartLoader implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
ApplicationContext ctx = contextRefreshedEvent.getApplicationContext();
try { //启动消息队列监听
SimpleMessageListenerContainer listener = (SimpleMessageListenerContainer) ctx.getBean("listenerA");
listener.start();
}catch (Exception e){
System.out.println("启动消息队列监听失败。",e);
}
}
}
就这样我们的监听类就在启动的时候成功的加载上Redis这个bean啦~