Attach the code directly
/** * @param subkey Set Key name * @param timeout get lock timeout,if not get, * @param the unit time unit * @para
M svalue * @return/public static Boolean Trylock (String subkey, String Svalue,long Timeout, Timeunit unit) {
String key = subkey;
Jedis Jedis = null;
try {Jedis = GetResource ();
if (Jedis = = null) {return boolean.false;
Long nano = System.nanotime ();
do {logger.debug ("Try Lock key:" + key); Long i = jedis.setnx (key, svalue); Deadlock may occur here (after performing setnx, Redis crash, key always exists) if (i = = 1) {Jedis.expire (key, 5);/Lock Expiration Time 5 sec logger.debug ("get
Lock, Key: "+ key +", expire in "+ 2 +" seconds ");
return boolean.true;
//Resolve deadlock problem can be optimized for Getset mode reset value//key existence, get key content value, value is Nanotime nanosecond, current time-key value > lock time, can acquire lock
String value = Jedis.get (key); if (Stringutils.isnotblank (value) &&!
Nil ". Equalsignorecase (value) && (System.nanotime ()-long.valueof (value)) >timeunit.seconds.tonanos (5)) {Set (key, value, 5);//Set key 5-second expiration automatic release
return boolean.true;
if (timeout = = 0) {//Lock is not taken, do not wait, return directly.
Break } thread.sleep ((int) (50*math.random () +50))//wait 50-100 milliseconds to avoid the same race time for different threads (System.nanotime ()-Nano) <
Unit.tonanos (timeout));//wait until the lock is taken until timeout if (logger.isinfoenabled ()) {String desc = jedis.get (key);
Logger.debug ("key:" + key + "locked by another business:" + desc);
return boolean.false;
}catch (Exception e) {logger.error (E.getmessage (), E);
finally {Returnresource (Jedis);/free connection} return boolean.false; /** get key corresponding value, the ratio content, the same delete, release the lock, avoid deleting other threads have acquired the lock * @param subkey * @param svalue * * Public stat
IC boolean UnLock (String subkey,string svalue) {string key = subkey;
Jedis Jedis = null;
try {Jedis = GetResource (); if (Jedis = null) {RETUrn false;
String str = jedis.get (subkey);
if (Str.equals (svalue)) {Jedis.del (key);
Logger.debug ("Release lock, Keys:" + key);
return true;
}else {logger.debug ("The key is not exist,key:" + key);
The catch (Exception e) {logger.error (E.getmessage (), E);
finally {Returnresource (Jedis);/free connection} return false;
public static void Main (string args[]) {string svalue = String.valueof (System.nanotime ());
String subkey = "ProductId";
try {//5000 ms Boolean lock = Trylock (subkey, Svalue, 5000, timeunit.milliseconds);
if (lock) {//do job related business logic} catch (Exception e) {e.printstacktrace ();
}finally{UnLock (subkey, svalue);
}
}