Mongo Distributed Lock Java Implementation

Source: Internet
Author: User

Mongo Distributed Lock Java Implementation
I. Application scenarios of distributed locks: II. required technologies:

1 <! -- Begin do start --> 2 <dependency> 3 <groupId> org. springframework. data </groupId> 4 <artifactId> spring-data-mongodb </artifactId> 5 <version> 1.8.2.RELEASE </version> 6 </dependency> 7 <dependency> 8 <groupId> org. springframework. data </groupId> 9 <artifactId> spring-data-commons </artifactId> 10 <version> 1.10.0.RELEASE </version> 11 </dependency> 12 <dependency> 13 <groupId> org. mongodb </groupId> 14 <artifactId> mongo -Java-driver </artifactId> 15 <version> 2.20.- rc2 </version> 16 </dependency> 17 <! -- Terminate do -->
View Code 3. Implementation Code:

The main implementation logic and external call methods, get the lock call getLock, release the lock call releaseLock, details are as follows:

1 import java. util. hashMap; 2 import java. util. list; 3 import java. util. map; 4 5 6 public class implements distributedlock {7 8 static implements lockdao; 9 10 static {11 implements lockdao = SpringBeanUtils. getBean ("unlock lockdao"); 12} 13 14/** 15 * steps to obtain the lock: 16*1. First, determine whether the lock is obtained by other requests; if it is not obtained by other requests, proceed to the next step. 17*2. Determine whether the lock resource expires. If it expires, release the lock resource. 18*3.1. Try to obtain the lock resource, if the value is 1, the lock resource is obtained normally. (if the current request has obtained the lock, other requests may attempt to obtain the lock, this will cause the expiration time of the Current lock to be Can be ignored because the extended time is within milliseconds .) 19*3.2, value> 1, indicates that the current request has obtained the lock resource while attempting to obtain the lock resource, that is, the current request has not obtained the lock; 20 *!!! Note: When you do not need to lock resources, release the lock resources in time !!!. 21*22 * @ param key23 * @ param expire24 * @ return25 */26 public static boolean getLock (String key, long expire) {27 List <shortlock> shortlocks = shortlockdao. getByKey (key); 28 // determines whether the lock is obtained. if the lock has been obtained by other requests, 29 if (unlock locks. size ()> 0 & amp; unlock locks. get (0 ). getExpire ()> = System. currentTimeMillis () {30 return false; 31} 32 // release the expired lock 33 if (unlock locks. size ()> 0 & amp; unlock locks. get (0 ). getExpire () <System. cur Effectimemillis () {34 releaseLockExpire (key, System. currentTimeMillis (); 35} 36 //!! (Under the premise of high concurrency) when the current request has obtained the lock, there may be other requests trying to obtain the lock, which will prolong the expiration time of the Current lock, because the extended time is within milliseconds, it can be ignored. 37 Map <String, Object> mapResult = export lockdao. incrByWithExpire (key, 1, System. currentTimeMillis () + expire); 38 // if the result is 1, the current request obtains the lock 39 if (Integer) mapResult. get ("value") = 1) {40 return true; 41 // if the result is greater than 1, it indicates that the lock has been obtained by other requests during the process of obtaining the lock. 42} else if (Integer) mapResult. get ("value")> 1) {43 return false; 44} 45 return false; 46} 47 48/** 49 * release lock 50*51 * @ param key52 */53 public static void releaseLock (String key) {54 Map <String, object> condition = new HashMap <> (); 55 condition. put ("key", key); 56 cipher lockdao. remove (condition); 57} 58 59/** 60 * release expiration lock 61*62 * @ param key63 * @ param expireTime64 */65 private static void releaseLockExpire (String key, long expireTime) {66 blocks lockdao. removeExpire (key, expireTime); 67} 68}
View Code

MongoLockDao implementation code:

1 import org. springframework. data. mongodb. core. findAndModifyOptions; 2 import org. springframework. data. mongodb. core. query. criteria; 3 import org. springframework. data. mongodb. core. query. query; 4 import org. springframework. data. mongodb. core. query. update; 5 import org. springframework. stereotype. repository; 6 7 import java. util. hashMap; 8 import java. util. list; 9 import java. util. map; 10 11 12 @ Reposito Ry13 public class implements lockdao <shortlock> {14 private Class <?> Clz; 15 16 public Class <?> GetClz () {17 if (clz = null) {18 // obtain the generic Class Object 19 clz = (Class <?>) 20 (ParameterizedType) (this. getClass (). getGenericSuperclass ())). getActualTypeArguments () [0]); 21} 22 return clz; 23} 24 25/** 26 * return data of the specified key 27*28 * @ param key29 * @ return30 */31 public List <shortlock> getByKey (String key) {32 Query query = new Query (); 33 query. addCriteria (Criteria. where ("key "). is (key); 34 return (List <shortlock>) Validate template. find (query, getClz (); 35} 36 37 38/** 39 * specify the key auto-increment (atomic addition ), and set the expiration time to 40*41 * @ param key42 * @ param increment43 * @ param expire44 * @ return45 */46 public Map <String, Object> incrByWithExpire (String key, double increment, long expire) {47 // filter 48 Query query = new Query (); 49 query. addCriteria (new Criteria ("key "). is (key); 50 51 // Update 52 update Update = new update (); 53 Update. inc ("value", increment); 54 update. set ("expire", expire); 55 // optional 56 FindAndModifyOptions options = FindAndModifyOptions. options (); 57 // 58 options is added if no options exist. upsert (true); 59 // return the updated value 60 options. returnNew (true); 61 Map <String, Object> resultMap = new HashMap <> (); 62 resultMap. put ("value", Double. valueOf (unlock lock) 63 encode template. findAndModify (query, update, options, getClz ())). getValue ()). intValue (); 64 resultMap. put ("expire", Long. valueOf (unlock lock) 65 seconds template. findAndModify (query, update, options, getClz ())). getExpire ()). longValue (); 66 return resultMap; 67} 68 69 70/** 71 * Delete expired Content Based on value 72*73 * @ param key74 * @ param expireTime75 */76 public void removeExpire (String key, long expireTime) {77 Query query = new Query (); 78 query. addCriteria (Criteria. where ("key "). is (key); 79 query. addCriteria (Criteria. where ("expire "). lt (expireTime); 80 validate template. remove (query, getClz (); 81} 82 83 public void remove (Map <String, Object> condition) {84 Query query = new Query (); 85 Set <Map. entry <String, Object> set = condition. entrySet (); 86 int flag = 0; 87 for (Map. entry <String, Object> entry: set) {88 query. addCriteria (Criteria. where (entry. getKey ()). is (entry. getValue (); 89 flag = flag + 1; 90} 91 if (flag = 0) {92 query = null; 93} 94 signature template. remove (query, getClz (); 95} 96 97}
View Code

Unlock lock entity:

 1 public class MongoLock { 2  3     private String key; 4     private double value; 5     private long expire; 6  7     public double getValue() { 8         return value; 9     }10 11     public void setValue(double value) {12         this.value = value;13     }14 15     public long getExpire() {16         return expire;17     }18 19     public void setExpire(long expire) {20         this.expire = expire;21     }22 23     public String getKey() {24         return key;25     }26 27     public void setKey(String key) {28         this.key = key;29     }30 }
View Code 4. Design Ideas

Premise: Use mongo to implement id auto-increment and the auto-increment process is atomic, that is, thread security.

Lock expiration time:

If the Code 1 releaseLockExpire (key, System. currentTimeMillis () in the figure is changed to releaseLockExpire (key), that is, when the lock is released, no expiration time is passed in, the following situation occurs:

 

 

Thank you! Add the original article link for reprinting. Thank you! Http://www.cnblogs.com/faaidong/p/7126716.html

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.