Redis Implements distributed locks

Source: Internet
Author: User
Tags getmessage

/** * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @version <b>1.0.0</b> * * public class Redisbilllockhandle R implements Ibatchbilllockhandler {private static final Logger Logger = Loggerfactory.getlogger (redisbilllockhand        Ler.class);            private static final int default_single_expire_time = 3;        private static final int default_batch_expire_time = 6;            Private final Jedispool Jedispool; /** * Construction * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL */Public Redisbilllockhandler (Jedispool Jedispool      ) {this.jedispool = Jedispool; }/** * Gets the lock if the lock is available immediately returns TRUE, otherwise false * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @param billid Entify * @return */public boolean trylock (Ibillidentify billidentify) {return Trylock (billidenti      FY, 0L, null); /** * Lock is idle for a given wait time, the acquisition lock succeeds returns TRUE, otherwise false * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @param bi LlidenTify * @param timeout * @param unit * @return */public boolean trylock (Ibillidentify billidentif          Y, long timeout, timeunit unit) {String key = (string) billidentify.uniqueidentify ();          Jedis Jedis = null;              try {Jedis = GetResource ();              Long nano = System.nanotime ();                  do {logger.debug ("Try Lock key:" + key);  Long i = jedis.setnx (key, key);                      Only set if if not present (i = = 1) {Jedis.expire (key, Default_single_expire_time);                      Logger.debug ("Get Lock, Key:" + key + ", expire in" + Default_single_expire_time + "seconds.");                  return boolean.true;                           } else {//Presence lock if (logger.isdebugenabled ()) {String desc = jedis.get (key);                      Logger.debug ("key:" + key + "locked by another business:" + desc);    }              } if (timeout = = 0) {break;              } thread.sleep (300);              } while ((System.nanotime ()-Nano) < Unit.tonanos (timeout));          return boolean.false;              } catch (Jedisconnectionexception je) {logger.error (Je.getmessage (), je);          Returnbrokenresource (Jedis);          } catch (Exception e) {logger.error (E.getmessage (), E);          } finally {Returnresource (Jedis);      } return boolean.false;      }/** * If lock idle immediately returns get failed wait * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @param billidentify          */public void Lock (Ibillidentify billidentify) {string key = (string) billidentify.uniqueidentify ();          Jedis Jedis = null;              try {Jedis = GetResource ();                  do {logger.debug ("Lock key:" + key); Long i = jedis.setnx (key, key);                      if (i = = 1) {Jedis.expire (key, Default_single_expire_time);                      Logger.debug ("Get Lock, Key:" + key + ", expire in" + Default_single_expire_time + "seconds.");                  Return                          } else {if (logger.isdebugenabled ()) {String desc = jedis.get (key);                      Logger.debug ("key:" + key + "locked by another business:" + desc);               }} thread.sleep (300);          } while (true);              } catch (Jedisconnectionexception je) {logger.error (Je.getmessage (), je);          Returnbrokenresource (Jedis);          } catch (Exception e) {logger.error (E.getmessage (), E);          } finally {Returnresource (Jedis); }}/** * Release lock * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @param billidentify * * Pub LIC void UnLock (Ibillidentify billidentify) {list<ibillidentify> List = new Arraylist<ibillidentify> (          );          List.add (billidentify);      UnLock (list); }/** * Bulk get lock If all gets immediately returns true, partial get failure returns false * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @date 2013-7-22 pm 10:27:44 * @param billidentifylist * @return * */public boolean trylock (List<ibillidenti      Fy> billidentifylist) {return Trylock (billidentifylist, 0L, NULL); /** * Lock is idle for a given wait time, the acquisition lock returns true successfully, otherwise false * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @para M billidentifylist * @param timeout * @param unit * @return */public boolean trylock (List<ibi          Llidentify> billidentifylist, long timeout, timeunit unit) {Jedis Jedis = null;                try {list<string> needlocking = new copyonwritearraylist<string> (); list<string> locked = NEW copyonwritearraylist<string> ();              Jedis = GetResource ();              Long nano = System.nanotime ();                  Do {//build Pipeline, Batch submit Pipeline Pipeline = jedis.pipelined ();                      for (ibillidentify identify:billidentifylist) {string key = (string) identify.uniqueidentify ();                      Needlocking.add (key);                  PIPELINE.SETNX (key, key);                  } logger.debug ("Try Lock keys:" + needlocking);                  Submit Redis Execution Count list<object> results = Pipeline.syncandreturnall ();                      for (int i = 0; i < results.size (); ++i) {Long result = (long) results.get (i);                      String key = Needlocking.get (i);                          if (result = = 1) {//Setnx succeeds, obtains lock Jedis.expire (key, Default_batch_expire_time);       Locked.add (key);               }} needlocking.removeall (locked); Locked resource Removal if (Collectionutils.isempty (needlocking)) {return true                  ; } else {//partial resource failed to lock Logger.debug ("keys:" + needlocking + "locked by Anoth                  ER business: ");                  } if (timeout = = 0) {break;                } thread.sleep (500);                } while ((System.nanotime ()-Nano) < Unit.tonanos (timeout)); Cannot get the lock, release the locked part of the object, and return the failed if (!              Collectionutils.isempty (Locked)) {Jedis.del (Locked.toarray (new string[0]));          } return false;              } catch (Jedisconnectionexception je) {logger.error (Je.getmessage (), je);          Returnbrokenresource (Jedis); } catch (Exception e) {logger.error (E.getmEssage (), E);          } finally {Returnresource (Jedis);      } return true; }/** * Bulk release lock * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @param billidentifylist */Publ IC void UnLock (list<ibillidentify> billidentifylist) {list<string> keys = new COPYONWRITEARRAYLIST&L T          String> ();              for (ibillidentify identify:billidentifylist) {string key = (string) identify.uniqueidentify ();          Keys.add (key);          } Jedis Jedis = null;              try {Jedis = GetResource ();              Jedis.del (Keys.toarray (new string[0]));          Logger.debug ("Release lock, Keys:" + keys);              } catch (Jedisconnectionexception je) {logger.error (Je.getmessage (), je);          Returnbrokenresource (Jedis);          } catch (Exception e) {logger.error (E.getmessage (), E);      } finally {Returnresource (Jedis);    }}/** * @author http://blog.csdn.net/java2000_wl * @date 2013-7-22 pm 9:33:45 * @retur      n */Private Jedis getresource () {return jedispool.getresource ();  }/** * Destroy connection * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @param jedis */private void          Returnbrokenresource (Jedis Jedis) {if (Jedis = = null) {return;          } try {//Fault tolerant Jedispool.returnbrokenresource (Jedis);          } catch (Exception e) {logger.error (E.getmessage (), E); }}/** * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @param jedis * * private void Retu          Rnresource (Jedis Jedis) {if (Jedis = = null) {return;          } try {Jedispool.returnresource (Jedis);          } catch (Exception e) {logger.error (E.getmessage (), E);   }      }

  

Redis Implements distributed locks

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.