一篇文章带你搞定 jedis 连接池:JedisPool的学习
·
一、使用方式
1. 创建JedisPool连接池对象
2. 调用方法 getResource()方法获取Jedis连接
public class RedisTest {
@Test
public void test() {
// 1. 创建一个配置对象
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(20);
config.setMaxIdle(10);
// 2. 创建 Jedis 连接池对象
JedisPool jedisPool = new JedisPool(config, "localhost", 6379);
// 3. 获取连接
Jedis jedis = jedisPool.getResource();
// 4. 使用
jedis.set("name","Jack");
// 5. 关闭归还到连接池
jedis.close();
}
}
jedis 信息配置:
#最大活动对象数
redis.pool.maxTotal=1000
#最大能够保持idel状态的对象数
redis.pool.maxIdle=100
#最小能够保持idel状态的对象数
redis.pool.minIdle=50
#当池内没有返回对象时,最大等待时间
redis.pool.maxWaitMillis=10000
#当调用borrow Object方法时,是否进行有效性检查
redis.pool.testOnBorrow=true
#当调用return Object方法时,是否进行有效性检查
redis.pool.testOnReturn=true
#“空闲链接”检测线程,检测的周期,毫秒数。如果为负值,表示不运行“检测线程”。默认为-1.
redis.pool.timeBetweenEvictionRunsMillis=30000
#向调用者输出“链接”对象时,是否检测它的空闲超时;
redis.pool.testWhileIdle=true
# 对于“空闲链接”检测线程而言,每次检测的链接资源的个数。默认为3.
redis.pool.numTestsPerEvictionRun=50
#redis服务器的IP
redis.ip=xxxxxx
#redis服务器的Port
redis1.port=6379
二、连接池工具类
JDBCUtils.java
public class JedisPoolUtils {
private static JedisPool jedisPool;
static {
//读取配置文件
InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
//创建Properties对象
Properties pro = new Properties();
//关联文件
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//获取数据,设置到JedisPoolConfig中
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
//初始化JedisPool
jedisPool = new JedisPool(config, pro.getProperty("host"), Integer.parseInt(pro.getProperty("port")));
}
/**
* 获取连接方法
*/
public static Jedis getJedis() {
return jedisPool.getResource();
}
}
jedis.properties
host=127.0.0.1
port=6379
maxTotal=50
maxIdle=10
测试调用
public class RedisTest {
@Test
public void test() {
// 通过连接池工具类获取
Jedis jedis = JedisPoolUtils.getJedis();
// 使用
jedis.set("username","Jack");
// 关闭
jedis.close();
}
}
更多推荐
所有评论(0)