工具:
package cn.itcast.util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/*
工具类
加载配置文件
*/
public class JedisPoolUtils {
private static JedisPool jedisPool;
static {
InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("cn/itcast/jedis.properties");
Properties pro = new Properties();
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
jedisPool = new JedisPool(config, pro.getProperty("host"), Integer.parseInt(pro.getProperty("port")));
}
public static Jedis getJedis(){
return jedisPool.getResource();
}
}
测试类
@Test
public void test8(){
Jedis jedis = JedisPoolUtils.getJedis();
//3.使用
jedis.set("hehe","hello");
//归还
jedis.close();
}
放在src文件下位置(如下图)可能会报错:java.lang.ExceptionInInitializerError,此时可将文件放到util文件下即可。(可能是JVM此时找不到你需要的配置文件的位置)