SpringData-Redis发布订阅自动重连分析

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值