redis在项目中其实用到的地方很多,但是用法还是不能够熟悉,现在写篇博客来复习复习。(使用的是jedis连接池)
首先,先导入jar包依赖。
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
首先建立一个jedis初始化类,来对jedis进行配置,初始化,封装方法。
public class RedisPool{
private static JedisPool pool;//jedis连接池
private static Integer maxTotal="连接池中最大的连接数";
private static Integer maxIdle="连接池最大的空闲jedis实例数";
private static Integer minIdle="连接池最小的空闲jedis实例数";
private static Boolean testonBorrow="在获得一个jedis实例之前是否进行测试";
private static Boolean testOnReturn="在放回一个Jedis实例之前是否进行测试";
private static Integer redisPort=6379;
private static Stirng redisIp="127.0.0.1";
private static initJedisPool(){
JdeisPoolConfig config=new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setTestOnBorrow(testonBorrow);
config.setTestOnReturn(testOnReturn);
config.setBlockWhenExhausted(true);//连接耗尽时候,true为阻塞直到超时,false为抛出错误
pool=new JedisPool(config,redisIp,redisPort,1000*2);//设置超时时间为两秒
}
static{
initJedisPool();
}
public static Jedis getJedis(){
return pool.getResource();
}
public static void close(){
pool.close();//在3.0之后就不推荐returnResource方法了
}
接着可以封装一个工具类来使用。
public class RedisPoolUntil{
public static String set(String key,String value){
Jedis jedis=null;
String result=null;
try{
jedis=RedisPool.getJedis();
result=jedis.set(key,value);
}catch(Exception e){
RedisPool.close();
}
return result;
}
public static String get(String key){
Jedis jedis=null;
String result=null;
try{
jedis=RedisPool.getJedis();
result=jedis.get(key);
}catch(Exception e){
RedisPool.close();
}
return result;
}
public static String setEx(String key,String value,int time){
Jedis jedis=null;
String result=null;
try{
jedis=RedisPool.getJedis();
result=jedis.setex(key,time,value);//记得是秒
}catch(Exception e){
RedisPool.close();
}
return result;
}
public static String del(String key){
Jedis jedis=null;
String result=null;
try{
jedis=RedisPool.getJedis();
result=jedis.del(key);
}catch(Exception e){
RedisPool.close();
}
return result;
}
public static Long expire(String key,int time){
Jedis jedis=null;
Long result=null;
try{
jedis=RedisPool.getJedis();
result=jedis.rxpire(key,time);
}catch(Exception e){
RedisPool.close();
}
return result;
}
}