Two ways to implement distributed locks __ Distributed

Source: Internet
Author: User
Because of the project, so today we talk about the two ways of implementing distributed locks. A kind of implementation using database lock, a single thread mechanism using Redis. Two ways can be implemented simultaneously in a project. The way in which configuration file control is used facilitates switching to another way when an exception occurs.
Distributed lock use scenario: the so-called distributed lock, is a distributed system or the use of the lock in the cluster, to lock the shared resources, such as the progress of the project, no order is to modify the same project progress, so the project schedule must be added lock. If you have only one server, you do not need to use distributed locks to lock shared resources.         On a single server, you can use the program lock in Java to lock down methods that modify the progress of a project, and control only one thread at a time to call this method. If more than one server, that is, more than one application to handle the user's request, the two applications can be processed at the same time to deal with two user requests, at this time two threads can modify the project progress. Java program locks do not work in this case. Need to be solved with distributed locks. A distributed lock can be used to resolve concurrency problems when multiple threads can simultaneously manipulate shared resources.
Implementation of ideas: two ideas, corresponding to two solutions. 1, the use of the database lock: ① to establish a lock table Tb_lock (Id,lock_class (lock Class), class_lock_id (lock the line of data Unique identification)) ② use the database Select FOR UPDATE statement to obtain TB_ Lock locks (for locked rows plus exclusive locks) 2, using Redis's single-threaded mechanism to implement a lock. Since Redis is single-threaded, it is single-threaded to access key-value, and multiple threads requesting redis do not have a competition problem. So you can set up a logo as a lock, the shared resource cannot be manipulated until the lock is acquired, and the thread that does not get the lock is in the state of the lock until the last thread releases the lock (that is, the latter thread can fetch the lock) or the lock is no longer taken over the specified timeout period. Implement://Call the lock place; Choose to use the SQL lock or Redis lock if (sysconfutil.getconfmsg ("LockType") according to the profile switch. Equals ("0")) {//sql lock          //parameters Financingid users to lock specific items (for public resources)          receivemap= Orderservice.sqllock (Financingid);  }else if (sysconfutil.getconfmsg ("LockType"). Equals ("1") {//redis lock           Receivemap=orderservice.redislock ( financingid); //sqllockorderpaysucess implementation     @Transactional  //(transactions must be used)     public map <string, object>  sqllock (string financingid)  throws exception{        &nBsp Map<string, object> returndata = new hashmap<string, object> ();         ISqlLockHandler sqlLock =  (Isqllockhandler) Springutil.getobject ("Sqllockhandler");         boolean boo = sqllock.trylock ("SqlLockFlag", financingid );         if (Boo) {//Get lock and execute business              returndata=this.xxx ();//Business method         } else{            logger.info ("Sqllock Get SQL Distributed lock failed") ;             returndata.put ("flag",  true);             returndata.put ("MSG", ) Failed to get SQL Distributed lock ");              throw new runtimeexception ("Get SQL Distributed lock failed");         }          return  returnData;     }
Redislockorderpaysucess implements @Transactional (propagation=propagation.not_supported)  //(Cannot use transactions, Otherwise the spring transaction timeout is likely to occur     public map<string, object>  redislock ( String financingid)   throws exception{        map <String, Object> returnData = new HashMap<String, Object> ();         //  Get redis  Connection object          IbatisRedisClient ibatisRedisClient =  (ibatisredisclient)  springutil.getobject ("Ibatisrediscli_persistence");         //  Get distributed Lock Object          iredislockhandler lockhandler = new redislockhandler (ibatisRedisClient);         //  Lock is idle for a given wait time, get lock success   return true,  otherwise return false          if  (Lockhandler.trylock) ("Lock_" + "Sqllockflag"  +  "_" +financingid,  60, timeunit.seconds)         {             try              {                 returndata=this.xxx ();//Business method             }             catch  (exception e)              {                 throw e;             }              finally             {                 if (lockhandler!=null) {                   /release lock                      lockhandler.unlock ("Lock_" + "Sqllockflag"  +  "_" +financingid);                 }              }         }         else         {             logger.info ("Redislock acquire Redis Distributed lock failure");             returndata.put ("flag",  true);   &nbsP;         returndata.put ("msg",  "Redislock acquire Redis Distributed lock failure");             throw new runtimeexception (" Redislock acquire Redis Distributed lock failure ");         }              return returnData;     }

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.