JedisPoolUtils工具类
- 步骤及:
- 0.创建数据库连接池类的成员变量(使用后面作为对象)
- 1.加载配置文件,获取配置文件的参数,并将参数设置为成员变量(数据库连接池对象)的配置参数
- 2.提供获取数据库连接的方法
- 3.关闭连接:归还
- 需要的配置文件:jedis.properties
- 数据库需要的jar包:commons-pool2-2.3.jar和jedis-2.7.0.jar
public class JedisPoolUtils {
// 创建Jedispool成员变量
private static JedisPool JedisPool;
// 1.加载配置文件:静态代码块
static {
// 1.1 创建一个Properties对象
Properties pro = new Properties();
// 1.2 获取配置文件的连接
InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
// 1.3 设置连接池配置信息
JedisPoolConfig config = new JedisPoolConfig();
// 将字符串转为整型
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
// 1.4 设置好数据库连接池对象
JedisPool = new JedisPool(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));
}
// 2.获取连接的方法
public static Jedis getJedis(){
return JedisPool.getResource();
}
// 3.关闭连接
public static void close(Jedis jedis){
if (jedis != null){
jedis.close();
}
}
}