Java uses Redis to implement distributed locks

Source: Internet
Author: User
Tags current time getmessage redis

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

 }
			
			
		}


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.