序
本文主要研究一下jedis连接池的预热
预热
代码语言:javascript复制@Component
@Slf4j
public class JedisWarmUp implements CommandLineRunner {
@Autowired
JedisConnectionFactory jedisConnectionFactory;
@Override
public void run(String... args) throws Exception {
GenericObjectPoolConfig poolConfig = jedisConnectionFactory.getPoolConfig();
if (poolConfig == null) {
return ;
}
try {
DirectFieldAccessor accessor = new DirectFieldAccessor(jedisConnectionFactory);
JedisPool jedisPool = (JedisPool) accessor.getPropertyValue("pool");
if (jedisPool == null) {
log.info("jedisConnectionFactory.pool is null");
return;
}
int warmUpSize = poolConfig.getMaxIdle();
warmUp(jedisPool, warmUpSize);
} catch (Exception e) {
log.error("warmup jedisPool error:{}", e.getMessage());
}
}
private void warmUp(JedisPool jedisPool, int warmUpSize) {
List<Jedis> warmUpList = new ArrayList<>(warmUpSize);
for (int i=0; i< warmUpSize; i ) {
Jedis jedis = jedisPool.getResource();
jedis.ping();
warmUpList.add(jedis);
}
warmUpList.stream().forEach(jedis -> jedis.close());
}
}
这里取了maxIdle配置来进行预热,通过DirectFieldAccessor来获取jedisConnectionFactory对象的pool
小结
在高并发场景,通常需要对资源进行预热,比如数据库连接池、redis连接池、线程池等等,可以避免首次请求慢的问题。这里通过先从连接池借一批连接,然后归还一批连接来达到预热的目的。