Distributed lock 1 Java common technical solutions

Reprinted from: http://www.cnblogs.com/PurpleDream/p/5559352.html

 

Foreword:

      Because in normal work, online servers are deployed in multiple distributed locations, and often face the problem of data consistency in distributed scenarios, so distributed locks must be used to solve these problems. So I combined some experience in actual work and some information I saw on the Internet to make an explanation and summary. I hope this article can be convenient for my future reference, and if it can help others, it is also very good.

 

===================================================== ============Long dividing line================================== =======================================

 

text:

      The first step, its own business scenario:

      In my daily projects, the following business scenarios are currently involved:

      Scenario 1: For  example, assigning a task scenario. In this scenario, since it is the company's business background system, it is mainly used for the review work of the reviewers, the concurrency is not very high, and the task allocation rules are designed to be pulled by the reviewers each time they actively request, and then The server randomly selects tasks from the task pool for assignment. When you see this scene, you will feel that it is relatively simple, but in the actual allocation process, because it involves the problem of clustering by users, it is more complicated than what I described. However, in order to illustrate the problem, you can simplify the problem. Then in the process of use, it is mainly to avoid the problem that the same task is acquired by two reviewers at the same time. I ended up using distributed locks based on database resource tables to solve the problem.

      Scenario 2: For  example, the payment scenario. In this scenario, I provide the user with three mobile phone numbers to protect the user's privacy (these numbers are obtained from the operator and look the same as the real mobile phone number), and let the user choose one of them for purchase, the user After paying for the purchase, I need to assign the number selected by the user to the user, and at the same time release the number that is not selected. In this process, the number screened for the user must be exclusive to the current user within a certain period of time (within the normal time range of user screening), so as to ensure 100% availability after payment; at the same time, due to the availability of product resource pools Resources are limited, and the fluidity of resources must be maintained, that is, resources cannot be occupied by a certain user for a long time. For the design goal of the service, the first phase of the project can support at least requests with a peak qps of 300 when it goes online, and the user experience should be considered in the design process. I ended up using memecahed's add() method and distributed locks based on database resource tables to solve the problem.

      Scenario 3:  I have a data service with a daily call volume of 300 million, and the qps calculated by 86,400 seconds per day is about 4,000. Since the service's call volume during the day is significantly higher than that at night, the peak qps during the day and afternoon reaches 6,000, a total of There are 4 servers, and a single qps can reach more than 3000. I ended up using the distributed locks of redis's setnx() and expire() to solve the problem.

       Scenario 4: An upgraded version of Scenario 1 and Scenario 2. In this scenario, no payment is involved. However, due to the increase in the number of areas that need to be consistent in the process of resource allocation, and the design goal of the first phase is to reach the peak qps500, we need to further optimize the scene. I ended up using redis's setnx(), expire() and distributed locks based on database tables to solve the problem.

 

      看到这里,不管你觉得我提出的业务场景qps是否足够大,都希望你能继续看下去,因为无论你身处一个什么样的公司,最开始的工作可能都需要从最简单的做起。不要提阿里和腾讯的业务场景qps如何大,因为在这样的大场景中你未必能亲自参与项目,亲自参与项目未必能是核心的设计者,是核心的设计者未必能独自设计。如果能真能满足以上三条,关闭页面可以不看啦,如果不是的话,建议还是看完,我有说的不足的地方欢迎提出建议,我说的好的地方,也希望给我点个赞或者评论一下,算是对我最大的鼓励哈。

 

  第二步,分布式锁的解决方式:

      1. 首先明确一点,有人可能会问是否可以考虑采用ReentrantLock来实现,但是实际上去实现的时候是有问题的,ReentrantLock的lock和unlock要求必须是在同一线程进行,而分布式应用中,lock和unlock是两次不相关的请求,因此肯定不是同一线程,因此导致无法使用ReentrantLock。

      2. 基于数据库表做乐观锁,用于分布式锁。

      3. 使用memcached的add()方法,用于分布式锁。

      4. 使用memcached的cas()方法,用于分布式锁。(不常用) 

      5. 使用redis的setnx()、expire()方法,用于分布式锁。

      6. 使用redis的setnx()、get()、getset()方法,用于分布式锁。

      7. 使用redis的watch、multi、exec命令,用于分布式锁。(不常用) 

      8. 使用zookeeper,用于分布式锁。(不常用) 

     

      第三步,基于数据库资源表做乐观锁,用于分布式锁:

      1. 首先说明乐观锁的含义:

          大多数是基于数据版本(version)的记录机制实现的。何谓数据版本号?即为数据增加一个版本标识,在基于数据库表的版本解决方案中,一般是通过为数据库表添加一个 “version”字段来实现读取出数据时,将此版本号一同读出,之后更新时,对此版本号加1。

          在更新过程中,会对版本号进行比较,如果是一致的,没有发生改变,则会成功执行本次操作;如果版本号不一致,则会更新失败。

      2. 对乐观锁的含义有了一定的了解后,结合具体的例子,我们来推演下我们应该怎么处理:

          (1). 假设我们有一张资源表,如下图所示: t_resource , 其中有6个字段id, resoource,  state, add_time, update_time, version,分别表示表主键、资源、分配状态(1未分配  2已分配)、资源创建时间、资源更新时间、资源数据版本号。

          

         (4). 假设我们现在我们对id=5780这条数据进行分配,那么非分布式场景的情况下,我们一般先查询出来state=1(未分配)的数据,然后从其中选取一条数据可以通过以下语句进行,如果可以更新成功,那么就说明已经占用了这个资源

               update t_resource set state=2 where state=1 and id=5780。

         (5). 如果在分布式场景中,由于数据库的update操作是原子是原子的,其实上边这条语句理论上也没有问题,但是这条语句如果在典型的“ABA”情况下,我们是无法感知的。有人可能会问什么是“ABA”问题呢?大家可以网上搜索一下,这里我说简单一点就是,如果在你第一次select和第二次update过程中,由于两次操作是非原子的,所以这过程中,如果有一个线程,先是占用了资源(state=2),然后又释放了资源(state=1),实际上最后你执行update操作的时候,是无法知道这个资源发生过变化的。也许你会说这个在你说的场景中应该也还好吧,但是在实际的使用过程中,比如银行账户存款或者扣款的过程中,这种情况是比较恐怖的。

         (6). 那么如果使用乐观锁我们如何解决上边的问题呢?

               a. 先执行select操作查询当前数据的数据版本号,比如当前数据版本号是26:

                   select id, resource, state,version from t_resource  where state=1 and id=5780;

               b. 执行更新操作:

                   update t_resoure set state=2, version=27, update_time=now() where resource=xxxxxx and state=1 and version=26

               c. 如果上述update语句真正更新影响到了一行数据,那就说明占位成功。如果没有更新影响到一行数据,则说明这个资源已经被别人占位了。

      3. 通过2中的讲解,相信大家已经对如何基于数据库表做乐观锁有有了一定的了解了,但是这里还是需要说明一下基于数据库表做乐观锁的一些缺点:

          (1). 这种操作方式,使原本一次的update操作,必须变为2次操作: select版本号一次;update一次。增加了数据库操作的次数。

          (2). 如果业务场景中的一次业务流程中,多个资源都需要用保证数据一致性,那么如果全部使用基于数据库资源表的乐观锁,就要让每个资源都有一张资源表,这个在实际使用场景中肯定是无法满足的。而且这些都基于数据库操作,在高并发的要求下,对数据库连接的开销一定是无法忍受的。

          (3). 乐观锁机制往往基于系统中的数据存储逻辑,因此可能会造成脏数据被更新到数据库中。在系统设计阶段,我们应该充分考虑到这些情况出现的可能性,并进行相应调整,如将乐观锁策略在数据库存储过程中实现,对外只开放基于此存储过程的数据更新途径,而不是将数据库表直接对外公开。     

      4. 讲了乐观锁的实现方式和缺点,是不是会觉得不敢使用乐观锁了呢???当然不是,在文章开头我自己的业务场景中,场景1和场景2的一部分都使用了基于数据库资源表的乐观锁,已经很好的解决了线上问题。所以大家要根据的具体业务场景选择技术方案,并不是随便找一个足够复杂、足够新潮的技术方案来解决业务问题就是好方案?!比如,如果在我的场景一中,我使用zookeeper做锁,可以这么做,但是真的有必要吗???答案觉得是没有必要的!!!

 

      第四步,使用memcached的add()方法,用于分布式锁:

      对于使用memcached的add()方法做分布式锁,这个在互联网公司是一种比较常见的方式,而且基本上可以解决自己手头上的大部分应用场景。在使用这个方法之前,只要能搞明白memcached的add()和set()的区别,并且知道为什么能用add()方法做分布式锁就好。如果还不知道add()和set()方法,请直接百度吧,这个需要自己了解一下。

      我在这里想说明的是另外一个问题,人们在关注分布式锁设计的好坏时,还会重点关注这样一个问题,那就是是否可以避免死锁问题???!!!

      如果使用memcached的add()命令对资源占位成功了,那么是不是就完事儿了呢?当然不是!我们需要在add()的使用指定当前添加的这个key的有效时间,如果不指定有效时间,正常情况下,你可以在执行完自己的业务后,使用delete方法将这个key删除掉,也就是释放了占用的资源。但是,如果在占位成功后,memecached或者自己的业务服务器发生宕机了,那么这个资源将无法得到释放。所以通过对key设置超时时间,即便发生了宕机的情况,也不会将资源一直占用,可以避免死锁的问题。

     

      第五步,使用memcached的cas()方法,用于分布式锁:     

      下篇文章我们再细说!

 

      第六步,使用redis的setnx()、expire()方法,用于分布式锁:

      对于使用redis的setnx()、expire()来实现分布式锁,这个方案相对于memcached()的add()方案,redis占优势的是,其支持的数据类型更多,而memcached只支持String一种数据类型。除此之外,无论是从性能上来说,还是操作方便性来说,其实都没有太多的差异,完全看你的选择,比如公司中用哪个比较多,你就可以用哪个。

      首先说明一下setnx()命令,setnx的含义就是SET if Not Exists,其主要有两个参数 setnx(key, value)。该方法是原子的,如果key不存在,则设置当前key成功,返回1;如果当前key已经存在,则设置当前key失败,返回0。但是要注意的是setnx命令不能设置key的超时时间,只能通过expire()来对key设置。

      具体的使用步骤如下:

      1. setnx(lockkey, 1)  如果返回0,则说明占位失败;如果返回1,则说明占位成功

      2. expire()命令对lockkey设置超时时间,为的是避免死锁问题。

      3. 执行完业务代码后,可以通过delete命令删除key。

      这个方案其实是可以解决日常工作中的需求的,但从技术方案的探讨上来说,可能还有一些可以完善的地方。比如,如果在第一步setnx执行成功后,在expire()命令执行成功前,发生了宕机的现象,那么就依然会出现死锁的问题,所以如果要对其进行完善的话,可以使用redis的setnx()、get()和getset()方法来实现分布式锁。   

 

      第七步,使用redis的setnx()、get()、getset()方法,用于分布式锁:

      这个方案的背景主要是在setnx()和expire()的方案上针对可能存在的死锁问题,做了一版优化。

      那么先说明一下这三个命令,对于setnx()和get()这两个命令,相信不用再多说什么。那么getset()命令?这个命令主要有两个参数 getset(key,newValue)。该方法是原子的,对key设置newValue这个值,并且返回key原来的旧值。假设key原来是不存在的,那么多次执行这个命令,会出现下边的效果:

      1. getset(key, "value1")  返回nil   此时key的值会被设置为value1

      2. getset(key, "value2")  返回value1   此时key的值会被设置为value2

      3. 依次类推!

      介绍完要使用的命令后,具体的使用步骤如下:

      1. setnx(lockkey, 当前时间+过期超时时间) ,如果返回1,则获取锁成功;如果返回0则没有获取到锁,转向2。

      2. get(lockkey)获取值oldExpireTime ,并将这个value值与当前的系统时间进行比较,如果小于当前系统时间,则认为这个锁已经超时,可以允许别的请求重新获取,转向3。

      3. 计算newExpireTime=当前时间+过期超时时间,然后getset(lockkey, newExpireTime) 会返回当前lockkey的值currentExpireTime。

      4. 判断currentExpireTime与oldExpireTime 是否相等,如果相等,说明当前getset设置成功,获取到了锁。如果不相等,说明这个锁又被别的请求获取走了,那么当前请求可以直接返回失败,或者继续重试。

      5. 在获取到锁之后,当前线程可以开始自己的业务处理,当处理完毕后,比较自己的处理时间和对于锁设置的超时时间,如果小于锁设置的超时时间,则直接执行delete释放锁;如果大于锁设置的超时时间,则不需要再锁进行处理。

 

      第八步,使用redis的watch、multi、exec命令,用于分布式锁:

      下篇文章我们再细说!

 

      第九步,使用zookeeper,用于分布式锁:

      下篇文章我们再细说!

 

      第十步,总结:

      综上,关于分布式锁的第一篇文章我就写到这儿了,在文章中主要说明了日常项目中会比较常用到四种方案,大家掌握了这四种方案,其实在日常的工作中就可以解决很多业务场景下的分布式锁的问题。从文章开头我自己的实际使用中,也可以看到,这么说完全是有一定的依据。对于另外那三种方案,我会在下一篇关于分布式锁的文章中,和大家再探讨一下。

      常用的四种方案:

      1. 基于数据库表做乐观锁,用于分布式锁。

      2. 使用memcached的add()方法,用于分布式锁。

      3. 使用redis的setnx()、expire()方法,用于分布式锁。

      4. 使用redis的setnx()、get()、getset()方法,用于分布式锁。

      不常用但是可以用于技术方案探讨的:

      1. 使用memcached的cas()方法,用于分布式锁。 

      2. 使用redis的watch、multi、exec命令,用于分布式锁。

      3. 使用zookeeper,用于分布式锁。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326412233&siteId=291194637