SpringData-Redis发布订阅自动重连分析
RedisMessageListenerContainer
配置
@Bean
@Autowired
RedisMessageListenerContainer redisContainer(JedisConnectionFactory redisConnectionFactory, RedisMessageListener a) {
RedisMessageListenerContainer container
= new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
List<Topic> topics = Lists.newArrayList(new ChannelTopic(
CHANNEL),
new ChannelTopic(CHANNEL)
);
container.addMessageListener(new MessageListenerAdapter(a), topics);
return container;
}
启动分析
添加频道监听
//RedisMessageListenerContainer.java
public void addMessageListener(MessageListener listener, Collection<? extends Topic> topics) {
addListener(listener, topics);
lazyListen();
}
这个AddListener会 对Topic做一些记录,patternMapping, channelMapping,去重等等,然后最关键的一步:
//RedisMessageListenerContainer.java
//addListener
// check the current listening state
if (listening) {
subscriptionTask.subscribeChannel(channels.toArray(new byte[channels.size()][]));
subscriptionTask.subscribePattern(patterns.toArray(new byte[patterns.size()][]));
}
//RedisMessageListenerContainer.java
void subscribeChannel(byte[]... channels) {
if (channels != null && channels.length > 0) {
if (connection != null) {
synchronized (localMonitor) {
Subscription sub = connection.getSubscription();
if (sub != null) {
sub.subscribe(channels);
}
}
}
}
}
//JedisSubscription.java
protected void doSubscribe(byte[]... channels) {
jedisPubSub.subscribe(channels);
}
但是启动之前 这个listening=false。故该代码不生效。再看lazyListen方法:
//RedisMessageListenerContainer.java
private void lazyListen() {
boolean debug = logger.isDebugEnabled();
boolean started = false;
if (isRunni