Search code examples
spring-bootspring-data-redislettuce

use spring boot data redis Connect to the redis cluster problem


I used spring boot data redis to connect to the redis cluster, using version 2.1.3 The configuration is as follows:

@Bean
@Primary
public RedisConnectionFactory myLettuceConnectionFactory(GenericObjectPoolConfig poolConfig) {
    RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
    final List<String> nodeList = redisProperties.getCluster().getNodes();
    Set<RedisNode> nodes = new HashSet<RedisNode>();
    for (String ipPort : nodeList) {
        String[] ipAndPort = ipPort.split(":");
        nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1])));
    }
    redisClusterConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
    redisClusterConfiguration.setClusterNodes(nodes);
    redisClusterConfiguration.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());
    LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
            .commandTimeout(redisProperties.getTimeout())
            .poolConfig(poolConfig)
            .build();

    RedisClusterClient clusterClient ;

    LettuceConnectionFactory factory = new LettuceConnectionFactory(redisClusterConfiguration,clientConfig);
    return factory;
}

However, during the operation, a WARN exception message will always be received as follows:

error log

Well, this seems to be a problem with lettuce, How to map remote host & port to localhost using Lettuce,but I don't know how to use it in spring boot data redis. Any solution is welcome, thank you


Solution

  • I've got the answer, so let's define a ClinentRourse like this:

     MappingSocketAddressResolver resolver = MappingSocketAddressResolver.create(DnsResolvers.UNRESOLVED ,
                hostAndPort -> {
                    if(hostAndPort.getHostText().startsWith("172.31")){
                        return HostAndPort.of(ipStr, hostAndPort.getPort());
                    }
                    return hostAndPort;
                });
    
        ClientResources clientResources = ClientResources.builder()
                .socketAddressResolver(resolver)
                .build();
    

    Then through LettuceClientConfiguration.clientResources method set in, the normal work of the lettuce.