Redis加锁
customerM = BaseMemCached.setMLock(customerId);
/** * 个人账户表加锁 **/ public static CustomerM setMLock(Integer userId){ CustomerM customerM = (CustomerM)setLock(USER_M_USERID+userId, CustomerM.class); customerM.setAddPiggy(0); customerM.setAddPayoff(0); customerM.setAddAmountBase(0); customerM.setAddAmountCft(0); return customerM; }
public static Object setLock(String key,Class classes){ logger.info("加锁"+key+_LOCK); long result = JedisPoolClient.getInstance().setnx(key+_LOCK,System.currentTimeMillis()); try { long time = System.currentTimeMillis(); while (result != 1) { Thread.sleep(10); time = System.currentTimeMillis(); result = JedisPoolClient.getInstance().setnx(key+_LOCK,time); } logger.info("加锁\t"+key+_LOCK+"\t完成"); JedisPoolClient.getInstance().set(key+_LOCK,time,TIME_OUT); return JedisPoolClient.getInstance().get(key,classes); }catch (Exception e){ e.printStackTrace(); } return null; }
public long setnx(String key,Object obj){ Jedis jedis = jedisPool.getResource(); try { long l = jedis.setnx(key,StringUtil.bean2json(obj)); return l; }catch(JedisConnectionException e){ jedisPool.returnBrokenResource(jedis); jedis=null; logger.error("redis异常:"+e.getMessage()); e.printStackTrace(); }finally{ jedisPool.returnResource(jedis); } return -1; }
public boolean set(String key,Object obj,int seconds){ Jedis jedis = jedisPool.getResource(); try { jedis.setex(key,seconds,StringUtil.bean2json(obj)); return true; }catch(JedisConnectionException e){ jedisPool.returnBrokenResource(jedis); jedis=null; logger.error("redis异常:" + e.getMessage()); e.printStackTrace(); }catch(Exception e){ logger.error("Json封装失败:" + e.getStackTrace()); }finally{ jedisPool.returnResource(jedis); } return false; }
Redis解锁
BaseMemCached.updateAndUnlock(customerM);
/** * 个人账户修改并解锁 * */ public static void updateAndUnlock(CustomerM customerM){ logger.info("解锁"+USER_M_USERID+customerM.getCustomerId() + _LOCK); setMem(USER_M_USERID+customerM.getCustomerId(),customerM); delete(USER_M_USERID+customerM.getCustomerId()+_LOCK); }
protected static boolean setMem(String key,Object obj){ return JedisPoolClient.getInstance().set(key,obj); }
protected static void delete(String key){ JedisPoolClient.getInstance().delete(key); }
public boolean set(String key,Object obj){ Jedis jedis = jedisPool.getResource(); try { logger.info(key+":"+StringUtil.bean2json(obj)); jedis.set(key, StringUtil.bean2json(obj)); return true; }catch(JedisConnectionException e){ jedisPool.returnBrokenResource(jedis); jedis=null; logger.error("redis异常:" + e.getMessage()); e.printStackTrace(); }finally{ jedisPool.returnResource(jedis); } return false; }
public void delete(String key){ Jedis jedis = jedisPool.getResource(); try { jedis.del(key); }catch(JedisConnectionException e){ jedisPool.returnBrokenResource(jedis); jedis=null; logger.error("redis异常:"+e.getMessage()); e.printStackTrace(); }finally{ jedisPool.returnResource(jedis); } }
时间: 2024-10-05 19:30:31