Redis项目中的使用

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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值