redis入门篇数据库:redis(一)
java代码操作redis数据库:redis(二)
本篇:redis连接池(自带的JedisPool)与案例。
redis连接池:
public class TestRedisPool {
@Test
public void test7() {
JedisPoolConfig cfg=new JedisPoolConfig();//配置对象
cfg.setMaxTotal(50);
cfg.setMaxIdle(10);
//以上三步可以不用写 直接用默认值
JedisPool jdsp=new JedisPool(cfg,"127.0.0.1",6379);//连接池对象
Jedis jds=jdsp.getResource();//获取连接
//省略数据库操作
jds.close();//归还连接池
}
}
抽取工具类:
jedis.properties:
host=127.0.0.1
port=6379
maxTotal=50
maxIdle=10
JedisPoolUtils.java:
public class JedisPoolUtils {
private static JedisPool jdsp;
static {
//类加载时读取配置文件
InputStream ips=JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
Properties pro =new Properties();
try {
pro.load(ips);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//获取数据
JedisPoolConfig cfg=new JedisPoolConfig();
cfg.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
cfg.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
jdsp= new JedisPool(cfg, pro.getProperty("host"), Integer.parseInt(pro.getProperty("port")));
}
public static Jedis getJedis() {
return jdsp.getResource();
}
}
public class TestJdsUtils {
public static void main(String[] args) {
Jedis jds=JedisPoolUtils.getJedis();
jds.set("hello", "good game");
System.out.println(jds.get("hello"));
jds.close();
}
}
测试成功:
一个小案例: