Springboot2 整合redis发布订阅 解决订阅多个频道重复代码过多 创建很多bean问题

时间:2022-07-26
本文章向大家介绍Springboot2 整合redis发布订阅 解决订阅多个频道重复代码过多 创建很多bean问题,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

之前的写法 每个频道都要写个@bean 重复代码太多

import cn.tim.util.Constants;
import com.alibaba.druid.filter.config.ConfigTools;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
@ConditionalOnClass(RedisTemplate.class)
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${public-key}")
    private String publicKey;

    private static final String SEPARATOR = ",";
    private static final String HOST_PORT_SEPARATOR = ":";

    /**
     * redis 发布订阅配置
     */
    @Bean
    RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory lettuceConnectionFactory,
                                                                Map<String, MessageListenerAdapter> messageListenerAdapterMap) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(lettuceConnectionFactory);
        log.info("subscribe begin...");
        messageListenerAdapterMap.forEach((k, v) -> {
            log.info("redis subscribe for " + k);
            container.addMessageListener(v, new PatternTopic(k));
        });
        log.info("subscribe end");
        return container;
    }

    /**
     * 初始化订阅频道及处理方法适配器映射 注意方法名不存在会导致系统无法启动
     */
    @Bean
    Map<String, MessageListenerAdapter> messageListenerAdapterMap(RedisMessageReceiver redisMessageReceiver) {
        Map<String, MessageListenerAdapter> map = new HashMap<>(16);
        map.put(Constants.IOC_DISABLE_CHANNEL, new MessageListenerAdapter(redisMessageReceiver, "iocDisable"));
        map.put(Constants.API_SUB_CHANNEL, new MessageListenerAdapter(redisMessageReceiver, "apiSub"));
        map.put(Constants.IOC_ADD_CHANNEL, new MessageListenerAdapter(redisMessageReceiver, "iocAdd"));
        map.put(Constants.SOURCE_SUB_CHANNEL, new MessageListenerAdapter(redisMessageReceiver, "sourceSub"));
        map.put(Constants.PLUGIN_SUB_CHANNEL, new MessageListenerAdapter(redisMessageReceiver, "pluginSub"));
        map.put(Constants.IOC_REFRESH_CHANNEL, new MessageListenerAdapter(redisMessageReceiver, "iocRefresh"));
        map.put(Constants.TTPS_SUB_CHANNEL, new MessageListenerAdapter(redisMessageReceiver, "ttpsSub"));
        map.put(Constants.SOURCE_API_CHANNEL, new MessageListenerAdapter(redisMessageReceiver, "sourceApi"));
        map.put(Constants.PROXYCONF_SUB_CHANNEL, new MessageListenerAdapter(redisMessageReceiver, "proxyConfSub"));
        map.put(Constants.SYSLOG_CONFIDENCE_CHANNEL, new MessageListenerAdapter(redisMessageReceiver, "syslogConfidence"));
        map.put("test_pubsub", new MessageListenerAdapter(redisMessageReceiver, "test"));
        //重要 调用一次afterPropertiesSet 设置method.invoke
        //否则invoke为空 会nullPoint
        map.forEach((k, v) -> v.afterPropertiesSet());
        return map;
    }

}

写一个接受类

@Component
public class RedisMessageReceiver {

//前面配置的方法 每个都要有 这里就写一个示例
 public void iocDisable(String message) {

    }

}