SpringDataRedis 支持IPV6
项目需求
1、应用程序支持单机redis的ipv4和ipv6连接
2、应用程序支持哨兵模式的redis的ipv4和ipv6的连接
适配IPV6的哨兵模式
1、配置文件
spring:
redis:
sentinel:
master: mymaster
nodes:
- "[2400:379:1200::30]:15610"
- "[2400:379:1200::31]:15610"
- "[2400:379:1200::32]:15610"
password: 123456
timeout: 10000
lettuce:
pool:
max-active: 10000
max-idle: 200
min-idle: 100
max-wait: 2000
说明:①、ipv6的地址需要将按照图示格式来,不然会报yaml解析错误
②、解析不报错了,需要重写连接
2、错误堆栈
2、springdataredis不支持ipv6的核心代码
private List<RedisNode> createSentinels(RedisProperties.Sentinel sentinel) {
List<RedisNode> nodes = new ArrayList<>();
for (String node : sentinel.getNodes()) {
try {
// ipv6不支持
String[] parts = StringUtils.split(node, ":");
Assert.state(parts.length == 2, "Must be defined as 'host:port'");
nodes.add(new RedisNode(parts[0], Integer.parseInt(parts[1])));
}
catch (RuntimeException ex) {
throw new IllegalStateException("Invalid redis sentinel property '" + node + "'", ex);
}
}
return nodes;
}
3、解决支持IPV6哨兵模式
网络上大部分是自定义配置信息,然后重写redis连接。此处为了适配我们的自身需求,想通过修改源码的形式来解决。核心就是修改createSentinels方法里面的逻辑。分割IPV6格式,用com.google.common.net.HostAndPort.
package com.tongtech.common.redis;
import com.google.common.net.HostAndPort;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.SocketOptions;
import io.lettuce.core.TimeoutOptions;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import io.lettuce.core.resource.ClientResources;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.LettuceClientConfigurationBuilderCustomizer;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.ArrayList;
import java