话不多说上代码:
public class JedisUtils {
private JedisUtils() {
}
private static JedisPool pool;
static {
// 1.读取配置文件
ResourceBundle bundle = ResourceBundle.getBundle("jedis");
int maxTotal = Integer.parseInt(bundle.getString("redis.maxTotal"));
int maxIdle = Integer.parseInt(bundle.getString("redis.maxIdle"));
String host = bundle.getString("redis.host");
int port = Integer.parseInt(bundle.getString("redis.port"));
// 2.jedis连接池配置
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxTotal);
poolConfig.setMaxIdle(maxIdle);
pool = new JedisPool(poolConfig, host, port);
}
/**
* 获取 redis连接对象
*
* @return
*/
public static Jedis getJedis() {
return pool.getResource();
}
}
总结:
这里也是Java中单例模式的实现方式之一,把jedisPool连接池对象的初始化,写在静态代码块中,然后为工具类提供私有的构造方法,让这个工具类,在整个项目中,连接池对象的初始化创建有且只有一次,避免了在不同模块下,频繁创建连接池对象,对内存消耗的问题。
写的比较简陋,为了记录自己的学习过程,希望对通行路上的你有些微帮助。加油。