redis操作的工具类
import java.util.Map; import org.apache.log4j.Logger; import redis.clients.jedis.Jedis; import com.chanjet.gov.service.Const; public class RedisUtil { public static Logger logger = Logger.getLogger(RedisUtil.class); private Jedis jedis; private Jedis jedisForIP; private RedisHelper() {//每次从池里取新连接 this.jedis = Const.pool.getResource(); this.jedis.select(11); this.jedisForIP = this.jedis; } public static RedisHelper getInstance() { RedisHelper instance = new RedisHelper(); // if(!instance.jedis.isConnected()){ // instance.jedis.connect(); // } // // //如果读取失败,关闭并重新连接 // try{ // String v = instance.jedis.get("test_connect"); // }catch(Exception e){ // instance.jedis.close(); // instance.jedis.connect(); // } return instance; } public Jedis getClient() { return jedis; } public Jedis getClientForIP() { return jedisForIP; } public void saveCache(String k, String v) { try{ jedis.set(k, v); }catch (Exception e){ e.printStackTrace(); logger.error("saveCache",e); Const.pool.returnBrokenResource(jedis); }finally { Const.pool.returnResource(jedis); } } public void saveKeyCache(String id, String k, String v) { try{ jedis.hset(id, k, v); }catch (Exception e){ e.printStackTrace(); logger.error("saveKeyCache",e); Const.pool.returnBrokenResource(jedis); }finally { Const.pool.returnResource(jedis); } } public void saveAllKeyCache(String id, Map kv) { try{ jedis.hmset(id, kv); }catch (Exception e){ e.printStackTrace(); logger.error("saveAllKeyCache",e); Const.pool.returnBrokenResource(jedis); }finally { Const.pool.returnResource(jedis); } } public void clearKeyCache(String id, String k) { try{ jedis.hdel(id, k); }catch (Exception e){ e.printStackTrace(); logger.error("clearKeyCache",e); Const.pool.returnBrokenResource(jedis); }finally { Const.pool.returnResource(jedis); } } public String getCache(String k) { String v = ""; try{ v = jedis.get(k); }catch (Exception e){ e.printStackTrace(); logger.error("getCache",e); Const.pool.returnBrokenResource(jedis); }finally { Const.pool.returnResource(jedis); } return v; } public String getKeyCache(String id, String k) { String v = ""; try{ v = jedis.hget(id, k); }catch (Exception e){ e.printStackTrace(); logger.error("getKeyCache",e); Const.pool.returnBrokenResource(jedis); }finally { Const.pool.returnResource(jedis); } return v; } public Map getAllKeyCache(String id) { Map v = null; try{ v = jedis.hgetAll(id); }catch (Exception e){ e.printStackTrace(); logger.error("getAllKeyCache",e); Const.pool.returnBrokenResource(jedis); }finally { Const.pool.returnResource(jedis); } return v; // Map v = jedis.hgetAll(id); // return v; } public void clearCache(String id) { try{ jedis.del(id); }catch (Exception e){ e.printStackTrace(); logger.error("clearCache",e); Const.pool.returnBrokenResource(jedis); }finally { Const.pool.returnResource(jedis); } // jedis.del(id); } }
使用
String needLogin = RedisUtil.getInstance().getKeyCache(cid,"needJsonp"); String password = RedisUtil.getInstance().getKeyCache(id,"password");