简介
Jedis连接池技术jedisPool,其实他和我们曾经学习过的MySQL数据库连接池(c3p0,Druid等连接池技术类似),这个时候就是我们编程思想,连接池技术的体现了,他们大体思路相同,都是动态的从一个池子对象中拿取和归还连接,
想要复习连接池技术的可以看我曾经写的一篇博客
MySQL数据库连接池技术
还有之前写的一篇Jedis连接技术使用的博客
Jedis连接技术
举个栗子
@Test
public void test2(){
//加载连接池的配置对象
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//基本连接数量
jedisPoolConfig.setMaxIdle(10);
//最多连接数量
jedisPoolConfig.setMaxTotal(50);
//创建连接池对象
JedisPool jedisPool = new JedisPool(jedisPoolConfig,"localhost",6379);
//获取连接
Jedis jedis = jedisPool.getResource();
//下面就可以通过连接对象jedis来操作Redis数据库了
jedis.set("xiu", String.valueOf(16));
//.....
//关闭连接归还到连接池
jedis.close();
}
配置文件的详细配置
#最大活动对象数
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
编写数据库连接池工具类
这个操作就很类似于之前所学连接池技术的思想,哪怕我们使用连接池技术,采用上面的代码形式,我们依然要重复的编写加载配置文件,连接池创建,连接归还等代码,我们自己编写连接池工具类的目的就是为了减少重复调用的代码量.
工具类的编写栗子:
/**
* JedisPool工具类,
* 主要实现加载配置文件
* 设置配置文件
* 提供获取连接的方法
*/
public class JedisPoolUtils {
public static JedisPool jedisPool;
//加载配置文件
static {
//获取配置文件的输入流
InputStream inputStream= JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
//建立properties对象
Properties properties = new Properties();
try {
//对properties对象和输入流建立连接
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
//获取数据,加载到JedisPoolConfig对象之中
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//这里说明一下properties.getProperty("maxTotal")获取的是字符串
//但是我设置JedisPoolConfig对象时使用到了数字,
//所有调用Integer.parseInt方法把字符串强转为了数字
jedisPoolConfig.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal")));
jedisPoolConfig.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle")));
//初始化jedisPool
jedisPool = new JedisPool(jedisPoolConfig, properties.getProperty("host"), Integer.parseInt(properties.getProperty("port")));
}
/**
* 获取连接的方法
*/
public static Jedis getJedis(){
return jedisPool.getResource();
}
}
使用类
//获取连接
Jedis jedis = JedisPoolUtils.getJedis();
//下面就可以通过连接对象jedis来操作Redis数据库了
jedis.set("xiu", String.valueOf(16));
//.....
//关闭连接归还到连接池
jedis.close();
其实这些步骤和我们之前使用的MySQL数据库连接池是类似的