最近项目中本地代码需要获取到Jedis配置参数,特意从springboot启动跟踪的整个参数的初始化、赋值过程,特将知识点记录如下。
1.spring-boot-autoconfigure包下面集成了对redis客户端的config类,有Jedis,Lettuce,本次关注的是Jedis。
2.我们找到对应的配置类 JedisConnectionConfiguration,从下图可以看到注解中加入了连接池,和Jedis
@Configuration
@ConditionalOnClass({ GenericObjectPool.class, JedisConnection.class, Jedis.class })
class JedisConnectionConfiguration extends RedisConnectionConfiguration {
3.往下我们找到 createJedisConnectionFactory()方法,改方法完成了redis连接的初始化
private JedisConnectionFactory createJedisConnectionFactory() {
JedisClientConfiguration clientConfiguration = getJedisClientConfiguration();
if (getSentinelConfig() != null) {
return new JedisConnectionFactory(getSentinelConfig(), clientConfiguration);
}
if (getClusterConfiguration() != null) {
return new JedisConnectionFactory(getClusterConfiguration(), clientConfiguration);
}
return new JedisConnectionFactory(getStandaloneConfig(), clientConfiguration);
}
4.一路跟踪方法调用 getJedisClientConfiguration–>applyPooling()—>jedisPoolConfig()
private JedisPoolConfig jedisPoolConfig(RedisProperties.Pool pool) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(pool.getMaxActive());
config.setMaxIdle(pool.getMaxIdle());
config.setMinIdle(pool.getMinIdle());
if (pool.getTimeBetweenEvictionRuns() != null) {
config.setTimeBetweenEvictionRunsMillis(pool.getTimeBetweenEvictionRuns().toMillis());
}
if (pool.getMaxWait() != null) {
config.setMaxWaitMillis(pool.getMaxWait().toMillis());
}
return config;
}
5.在jedisPoolConfig()方法中完成了对配置参数的初始哈,方法入参RedisProperties类就保存了redis客户端的配置参数信息,所以我们只要获取到该类就能获取到jedisPool的配置参数了
@Component
public class RedisUtil {
@Autowired
private RedisProperties properties;
public Map<String,String> getJedisPoolProperties(){
Map<String,String> map = new HashMap<>();
map.put("maxIdle",String.valueOf(properties.getJedis().getPool().getMaxIdle()));
map.put("maxActive",String.valueOf(properties.getJedis().getPool().getMaxActive()));
map.put("maxWait",String.valueOf(properties.getJedis().getPool().getMaxWait()));
map.put("mainIdle",String.valueOf(properties.getJedis().getPool().getMinIdle()));
return map;
}
}
6.到此,我们本次获取jedisPool配置参数就大功告成了。