Redis Implement distributed lock __java

Source: Internet
Author: User
Tags getmessage redis

Original address: http://blog.csdn.net/java2000_wl/article/details/8740911

Reference Address:

Http://www.cnblogs.com/dolphin0520/p/3923167.html

http://phl.iteye.com/blog/2029944


/** * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @version <b>1.0.0</b> * * public class Redisbilllockhandler Implements Ibatchbilllockhandler {private static final Logger Logger = Loggerfactory.getlogger (redisbilllockhandler.cl

	ASS);
	
	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.je
	Dispool = Jedispool; /** * Acquire a lock returns true if the lock is available immediately, or FALSE * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @param billidentify * @re
	Turn * * Public boolean Trylock (Ibillidentify billidentify) {return Trylock (billidentify, 0L, NULL);  /** * Lock is idle for a given wait time, the fetch lock succeeds returns TRUE, otherwise it returns false * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @param billidentify * @param timeout * @param unit * @return/public boolean trylock (Ibillidentify billidentiFY, 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);
					if (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 {//exists 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 L
		Ock (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 * * public void UnLock (Ibilliden
		Tify billidentify) {list<ibillidentify> List = new arraylist<ibillidentify> ();
		List.add (billidentify);
	UnLock (list); /** * Bulk Fetch lock If all gets immediately returns true, partial fetch 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<ibillidentify> billidentifylist) {
	Return Trylock (billidentifylist, 0L, NULL); /** * Lock is idle for a given wait time, the fetch lock succeeds returns TRUE, otherwise it returns false * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @param billidentifylis T * @param timeout * @param unit * @return/public boolean trylock (List<ibillidentify> 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);
				Commit 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 successful, get lock Jedis.expire (key, Default_batch_expire_time);
					Locked.add (key);	} needlocking.removeall (Locked);
				Lock resource Removal if (Collectionutils.isempty (needlocking)) {return true;
				else {//Some resources could not be locked Logger.debug ("keys:" + needlocking + "locked by another business:");
				} if (timeout = = 0) {break; }
				Thread.Sleep (500);

			while ((System.nanotime ()-Nano) < Unit.tonanos (timeout)); The lock is not unlocked, releasing the locked part of the object and returning 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 * * public void UnLock (LIST&L
		T;ibillidentify> billidentifylist) {list<string> keys = new copyonwritearraylist<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 * @return * * Private Jedis get
	Resource () {return jedispool.getresource (); /** * Destroy connection * @author HTTP://BLOG.CSDN.NET/JAVA2000_WL * @param jedis/private void Returnbrokenresource (Je
		Dis 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 Returnresource (Jedis Jedis) {
		if (Jedis = = null) {return;
		try {jedispool.returnresource (Jedis);
		catch (Exception e) {logger.error (E.getmessage (), E); }
	}






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.