首页 > 数据库 >springboot链接redis IPV6

springboot链接redis IPV6

时间:2024-04-26 15:56:13浏览次数:27  
标签:return springboot builder redis private IPV6 new null properties

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
package org.springframework.boot.autoconfigure.data.redis;

/**
 * 解决Jredis配置文件,不兼容IPV6地址的BUG
 */
@Slf4j
@Configuration
@ConditionalOnClass({GenericObjectPool.class, JedisConnection.class, Jedis.class})
@AutoConfigureOrder(value = Ordered.HIGHEST_PRECEDENCE)
public class MsfJedisConnectionConfiguration extends RedisConnectionConfiguration {

    private final RedisProperties properties;

    public MsfJedisConnectionConfiguration(RedisProperties properties,
                                           ObjectProvider<RedisSentinelConfiguration> sentinelConfiguration,
                                           ObjectProvider<RedisClusterConfiguration> clusterConfiguration) {
        super(properties, sentinelConfiguration, clusterConfiguration);
        this.properties = properties;
    }

    @Bean
    public JedisConnectionFactory redisConnectionFactory(
            ObjectProvider<JedisClientConfigurationBuilderCustomizer> builderCustomizers) throws UnknownHostException {
        return createJedisConnectionFactory(builderCustomizers);
    }

    private JedisConnectionFactory createJedisConnectionFactory(
            ObjectProvider<JedisClientConfigurationBuilderCustomizer> builderCustomizers) {
        JedisClientConfiguration clientConfiguration = getJedisClientConfiguration(builderCustomizers);
        if (getSentinelConfig() != null) {
            return new JedisConnectionFactory(getSentinelConfig(), clientConfiguration);
        }
        RedisClusterConfiguration redisClusterConfiguration = getClusterConfiguration1();
        if (redisClusterConfiguration != null) {
            Set<RedisNode> nodes=redisClusterConfiguration.getClusterNodes();
            log.info("clusterNodes:{}",nodes);
            log.info("password:{}",redisClusterConfiguration.getPassword());
            log.info("maxRedirects:{}",redisClusterConfiguration.getMaxRedirects());
            return new JedisConnectionFactory(redisClusterConfiguration, clientConfiguration);
        }
        return new JedisConnectionFactory(getStandaloneConfig(), clientConfiguration);
    }


    /**
     * Create a {@link RedisClusterConfiguration} if necessary.
     *
     * @return {@literal null} if no cluster settings are set.
     */
    protected final RedisClusterConfiguration getClusterConfiguration1() {
        if (properties == null) {
            return null;
        }
        RedisProperties.Cluster clusterProperties = properties.getCluster();
        if (clusterProperties != null) {
            MsfRedisClusterConfiguration config = new MsfRedisClusterConfiguration(clusterProperties.getNodes());
            if (clusterProperties.getMaxRedirects() != null) {
                config.setMaxRedirects(clusterProperties.getMaxRedirects());
            }
            if (properties.getPassword() != null) {
                config.setPassword(RedisPassword.of(properties.getPassword()));
            }
            return config;
        } else {
            return null;
        }
    }


    private JedisClientConfiguration getJedisClientConfiguration(
            ObjectProvider<JedisClientConfigurationBuilderCustomizer> builderCustomizers) {
        JedisClientConfigurationBuilder builder = applyProperties(JedisClientConfiguration.builder());
        RedisProperties.Pool pool = properties.getJedis().getPool();
        if (pool != null) {
            applyPooling(pool, builder);
        }
        if (StringUtils.hasText(properties.getUrl())) {
            customizeConfigurationFromUrl(builder);
        }
        builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
        return builder.build();
    }

    private JedisClientConfigurationBuilder applyProperties(JedisClientConfigurationBuilder builder) {
        if (properties.isSsl()) {
            builder.useSsl();
        }
        if (properties.getTimeout() != null) {
            Duration timeout = properties.getTimeout();
            builder.readTimeout(timeout).connectTimeout(timeout);
        }
        return builder;
    }

    private void applyPooling(RedisProperties.Pool pool,
                              JedisClientConfiguration.JedisClientConfigurationBuilder builder) {
        builder.usePooling().poolConfig(jedisPoolConfig(pool));
    }

    private JedisPoolConfig jedisPoolConfig(RedisProperties.Pool pool) {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(pool.getMaxActive());
        config.setMaxIdle(pool.getMaxIdle());
        config.setMinIdle(pool.getMinIdle());
        if (pool.getMaxWait() != null) {
            config.setMaxWaitMillis(pool.getMaxWait().toMillis());
        }
        return config;
    }

    private void customizeConfigurationFromUrl(JedisClientConfiguration.JedisClientConfigurationBuilder builder) {
        ConnectionInfo connectionInfo = parseUrl(properties.getUrl());
        if (connectionInfo.isUseSsl()) {
            builder.useSsl();
        }
    }

}
package org.springframework.boot.autoconfigure.data.redis;
/**
 * MsfRedisClusterConfiguration 
 */
@Slf4j
public class MsfRedisClusterConfiguration extends RedisClusterConfiguration {

    private static final String REDIS_CLUSTER_NODES_CONFIG_PROPERTY = "spring.redis.cluster.nodes";
    private static final String REDIS_CLUSTER_MAX_REDIRECTS_CONFIG_PROPERTY = "spring.redis.cluster.max-redirects";
    private Set<RedisNode> clusterNodes = new HashSet<>();

    public MsfRedisClusterConfiguration() {
    }

    public MsfRedisClusterConfiguration(Collection<String> clusterNodes) {
        this(new MapPropertySource("RedisClusterConfiguration", asMap(clusterNodes, -1)));
    }

    public MsfRedisClusterConfiguration(PropertySource<?> propertySource) {
        notNull(propertySource, "PropertySource must not be null!");

        this.clusterNodes = new HashSet<>();

        if (propertySource.containsProperty(REDIS_CLUSTER_NODES_CONFIG_PROPERTY)) {
            appendClusterNodes(
                    commaDelimitedListToSet(propertySource.getProperty(REDIS_CLUSTER_NODES_CONFIG_PROPERTY).toString()));
        }
        if (propertySource.containsProperty(REDIS_CLUSTER_MAX_REDIRECTS_CONFIG_PROPERTY)) {
            this.setMaxRedirects(NumberUtils.parseNumber(
                    propertySource.getProperty(REDIS_CLUSTER_MAX_REDIRECTS_CONFIG_PROPERTY).toString(), Integer.class));
        }
    }

    /**
     * 重写父类解析IP地址和端口号的代码,兼容IPV6地址
     *
     * @param node
     * @return
     */
    private RedisNode readHostAndPortFromString(String node) {

//		String[] args = split(hostAndPort, ":");
//
//		notNull(args, "HostAndPort need to be seperated by  ':'.");
//		isTrue(args.length == 2, "Host and Port String needs to specified as host:port");
//		return new RedisNode(args[0], Integer.valueOf(args[1]));

        HostAndPort hostAndPort = HostAndPort.fromString(node);
        String host = hostAndPort.getHostText();
        int port = hostAndPort.getPort();
        return new RedisNode(host, port);
    }

    /**
     * @param clusterHostAndPorts must not be {@literal null} or empty.
     * @param redirects           the max number of redirects to follow.
     * @return cluster config map with properties.
     */
    private static Map<String, Object> asMap(Collection<String> clusterHostAndPorts, int redirects) {

        notNull(clusterHostAndPorts, "ClusterHostAndPorts must not be null!");

        Map<String, Object> map = new HashMap<>();
        map.put(REDIS_CLUSTER_NODES_CONFIG_PROPERTY, StringUtils.collectionToCommaDelimitedString(clusterHostAndPorts));

        if (redirects >= 0) {
            map.put(REDIS_CLUSTER_MAX_REDIRECTS_CONFIG_PROPERTY, redirects);
        }

        return map;
    }

    protected void appendClusterNodes(Set<String> hostAndPorts) {

        for (String hostAndPort : hostAndPorts) {
            addClusterNodeCustomer(readHostAndPortFromString(hostAndPort));
        }
        this.setClusterNodes(this.clusterNodes);
    }


    /**
     * Add a cluster node to configuration.
     *
     * @param node must not be {@literal null}.
     */
    public void addClusterNodeCustomer(RedisNode node) {
        notNull(node, "ClusterNode must not be 'null'.");
        this.clusterNodes.add(node);
    }

}
/**
 * RedisConfig
 */
@Configuration
@Import({MsfJedisConnectionConfiguration.class, MsfRedisClusterConfiguration.class})
public class RedisConfig {
}

标签:return,springboot,builder,redis,private,IPV6,new,null,properties
From: https://www.cnblogs.com/MC-Bonnie/p/18160253

相关文章

  • redis系列02---缓存过期、穿透、击穿、雪崩
    一、缓存过期问题产生的原由:内存空间有限,给缓存设置过期时间,但有些键值运气比较好,每次都没有被我的随机算法选中,每次都能幸免于难,这可不行,这些长时间过期的数据一直霸占着不少的内存空间!解决方案:redis提供8种策略供应用程序选择,用于我遇到内存不足时该如何决策:*noeviction:返......
  • Redis分布式锁
    Redis分布式锁如何实现?在Redis中提供了一个命令setnx(SETifnotexists)由于Redis的单线程的,用了命令之后,只能有一个客户端对某一个key设置值,在没有过期或删除key的时候是其他客户端是不能设置这个key的。如何控制Redis实现分布式锁有效时长呢?Redis的setnx指令不好控制这个......
  • springBoot源码(一)
    构造函数运行代码publicConfigurableApplicationContextrun(String...args){ Startupstartup=Startup.create(); if(this.registerShutdownHook){ SpringApplication.shutdownHook.enableShutdownHookAddition(); } DefaultBootstrapContextbootstrapConte......
  • redis相关
    redis是一种nosql数据库,sql是关系型数据库,nosql是非关系型数据库,一般以键值对、json、图数据库等为主sql中会存储包含外键的关系表,nosql更多以键值对嵌套形式来表示关系,缺点是没有约束容易重复。从查询语句上来说sql格式较为固定,优点是只要是关系型数据库都能用相同的sql语句查......
  • redis
    一、redis为什么快1.基于内存:内存读写效率远高于磁盘读写2.存储形式:键值对的内存数据库,哈希表结构O(1)时间复杂度可以获取值3.单线程:避免上下文切换4.IO多路复用:单个线程处理多个客户端链接5.编码:支持多种数据结构及编码,根据元素数量,有阀值,大于小于阀值的编码不......
  • SpringBoot整合AOP实现打印方法执行时间切面
    pom.xml<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>代码创建注解importjava.lang.annotation.ElementType;importja......
  • Redis淘汰策略
    Redis过期策略有几种?Redis中提供八种过期策略,默认是noeviction,即不删除任何数据,当内存不足时会直接报错。可以在Redis的配置文件中进行设置。noeviction:不淘汰任何key,但是内存满时不允许写入新数据,默认就是这种策略。volatile-ttl:对设置了TTL的key,比较key的剩余TTL值,TTL越......
  • Redis场景
    redis应用场景Redis在缓存和队列方面有着广泛的应用场景,下面详细介绍一下:缓存应用场景:页面缓存:在Web应用中,Redis可以用作页面缓存,存储页面渲染结果,以减轻数据库的压力,提高页面响应速度。当用户请求某个页面时,首先检查Redis中是否存在该页面的缓存,如果存在则直接返回缓......
  • redis安装及使用
    Redis与传统数据库的一个主要区别在于,Redis把所有数据都存储在内存中,而传统数据库通常只会把数据的索引存储在内存中,并将实际的数据存储在硬盘中。为了满足不同的持久化需求,Redis提供了RDB持久化、AOF持久化和RDB-AOF混合持久化等多种持久化方式以供用户选择。如果用户有需要,也......
  • redis使用
    Pythonredis使用介绍|菜鸟教程(runoob.com)Python操作Redis,你要的都在这了!-John-Python-博客园(cnblogs.com)redis基本命令Stringset(name,value,ex=None,px=None,nx=False,xx=False)在Redis中设置值,默认,不存在则创建,存在则修改。参数:ex-过期时间(秒......