Main references:
- http://blog.csdn.net/fjssharpsword/article/details/52250723#
- Http://www.yiibai.com/redis/strings_getset.html
- Https://redis.io/commands/expire
- https://www.baidu.com/link?url=kuDPE2uEXfjZO3qCggv2OaDGcd9_Mohb_S2Web1VHiY623cg4IJZRwqb0_ Tgyan7x0bjuv1i46dh-qgwcpejsa&wd=&eqid=879de37e00008ea500000004583ef0f8
Packagecom.deppon.spring;ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.BlockingQueue;ImportJava.util.concurrent.RejectedExecutionHandler;ImportJava.util.concurrent.ThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit;ImportRedis.clients.jedis.Jedis;/** * * @authorGANXJ **/ Public classBuilddistributedlockwithredisdb {//Lock Name Private Static FinalString lockname = "Lock"; //Sequence name Private Static FinalString sequencename = "sequence"; //Data Failure Time Private Static Final intexpired = 1;//1-second timeout//The time it takes the current thread to process the cache operation, (pre-estimate) Private Static Final intTime = 10 * 1000; //setnx---When and only if key does not exist, set the value of key to value and return 1, and if the given key already exists, SETNX does nothing and returns 0. //Getset--Sets the value of the given key to value and returns the old value of key, which returns an error when key is present but not a string type, and returns nil when key does not exist. //locked Public Static BooleanAcquirelock (Jedis Jedis, String Lock) {Try { //used to set the cache processing duration after success LongCacheprocesstime = System.currenttimemillis () +Time ; //when key is empty, scramble for lock LongIssetsuccesswhilekeyisnil =jedis.setnx (lock, String.valueof (Cacheprocesstime)); //Setnx succeeds, it succeeds in acquiring a lock and setting the data expiration time if(Issetsuccesswhilekeyisnil = = 1) {Jedis.expire (lock, expired); return true; } //key is not NULL, SETNX failed, indicating that the lock was persisted by another client, check whether it has timed outString Lastlocktimebysomethread =Jedis.get (lock); //if get key is empty, the lock process when the key is re-run if(Lastlocktimebysomethread = =NULL) { return false; } //gets the key is not empty, then determines whether the timeout, if not timed out, the Loop retry if(Long.valueof (Lastlocktimebysomethread) >System.currenttimemillis ()) { return false; } //if timed out, scramble for lockString Getoldifset =Jedis.getset (lock, String.valueof (Cacheprocesstime)); //determine if the lock is successful if(Getoldifset! =NULL&&getoldifset.equals (Lastlocktimebysomethread)) { return true; } //flocculent Lock failed, start over again return false; } Catch(Exception e) {e.printstacktrace (); } return false; } //Release Lock Public Static voidReleaseLock (Jedis Jedis, String Lock) {Try{String Lastlocktimebysomethread=Jedis.get (lock); if(Lastlocktimebysomethread = =NULL) { return; } //avoid deleting locks that are not acquired by yourself if(System.currenttimemillis () <long.valueof (Lastlocktimebysomethread)) {Jedis.del (lock); } } Catch(Exception e) {e.printstacktrace (); }} @SuppressWarnings ("Resource") Public Static voidMain (string[] args) {//Number of tasks intProducetaskmaxnumber = 100; //initializing the ID sequence in RedisJedis Jedis =NewJedis (); Jedis.set (Sequencename, string.valueof (long.valueof (1))); //initializing the thread pool intCorepoolsize = 20; intMaximumpoolsize=20; LongKeepAliveTime =20; Timeunit Unit=Timeunit.seconds; Blockingqueue<Runnable> Workqueu =NewArrayblockingqueue<runnable> (30); Rejectedexecutionhandler Handler=NewThreadpoolexecutor.discardoldestpolicy (); Threadpoolexecutor ThreadPool=NewThreadpoolexecutor (corepoolsize, Maximumpoolsize, KeepAliveTime, Unit, Workqueu, handler); //Create a task for(inti = 1; I <= Producetaskmaxnumber; i++) { Try{Threadpool.execute (NewBuilddistributedlockwithredisdb ().NewRedislocktesttask ()); } Catch(Exception e) {e.printstacktrace (); } } } classRedislocktesttaskImplementsRunnable {@Override Public voidrun () {Jedis Jedis=NewJedis (); Boolean Lockflag=true; //round-robin waiting to get lock LongStartTime =System.currenttimemillis (); while(lockflag) {if(Builddistributedlockwithredisdb.acquirelock (Jedis, Lockname)) {//get the lock, start executing business logicprocess (Jedis, sequencename); Lockflag=false; } } LongEndTime =System.currenttimemillis (); System.out.println (Thread.CurrentThread (). GetName ()+ "Thread Set Value:" +jedis.get (sequencename)+ "+" Total consumption time: "+ (Endtime-starttime) +" MS "); //Release LockBuilddistributedlockwithredisdb.releaselock (Jedis, lockname); } } voidprocess (Jedis jedis,string sequencename) {jedis.set (Sequencename, string.valueof (long.valueof (Jedis.get (Sequen Cename))+ 1)); }}
Applying Redis to implement distributed locks