import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;
/**
* redis 连接池
* @date 2018年1月17日 上午9:29:03
*/
@Component
public class RedisConnectPools {
private static Logger log = LogManager.getLogger(RedisConnectPools.class);
private static JedisPool pool = null;
@Autowired
private RedisConfig redisConfig;
private void init() throws JedisConnectionException {
JedisPoolConfig config = new JedisPoolConfig();
// 控制一个 pool 可分配多少个 jedis 实例,通过 pool.getResource() 来获取;
// 如果赋值为 -1,则表示不限制;如果 pool 已经分配了 maxActive个jedis 实例,则此时 pool 的状态为 exhausted (耗尽)。
config.setMaxTotal(2000);
// 控制一个 pool 最多有多少个状态为 idle (空闲的)的 jedis 实例。
config.setMaxIdle(50);
// 表示当 borrow (引入)一个 jedis 实例时,最大的等待时间,如果超过等待时间,则直接抛出 JedisConnectionException;
config.setMaxWaitMillis(1000 * 100);
// 在 borrow 一个 jedis 实例时,是否提前进行 validate 操作;如果为 true,则得到的 jedis 实例均是可用的;
config.setTestOnBorrow(true);
pool = new JedisPool(config, redisConfig.getIp(), redisConfig.getPort(), 1000 * 100, redisConfig.getPsw());
}
/**
* 获取redis连接池对象
*
* @return
*/
public JedisPool getPool() {
if (pool == null) {
init();
}
return pool;
}
/**
* 获取Jedis对象
*
* @param dataBaseIndex 库索引
* @return
*/
public Jedis getJedisObj(int dataBaseIndex) {
JedisPool pool = null;
Jedis jedis = null;
pool = getPool();
jedis = pool.getResource();
jedis.select(dataBaseIndex);
log.info("redis连接池,Active:{},Idle:{},Waiters:{}",
pool.getNumActive(), pool.getNumIdle(), pool.getNumWaiters());
return jedis;
}
}
Redis 连接池配置(在 Spring Boot 框架中)
最新推荐文章于 2024-06-24 09:27:11 发布