Memcached and Redis distributed lock Scheme __ Cache

Source: Internet
Author: User
Tags memcached server memory

Distributed caching, can solve the single server memory can not be unlimited expansion of the bottleneck. In the application of distributed caching, multiple client contention issues are encountered. This time, need to use a distributed lock, the client has access to the lock to operate permissions.

Memcached and Redis are common distributed cache-building schemes, and the following are examples of implementation methods based on Memcached and Redis distributed locks.

Memcached Distributed Locks

Memcached can use the add command, which is added only if the key does not exist , or is not processed. Memcached All commands are atomic, and then add the same key, only one will succeed.

Using this principle, you can first define a lock Lockkey, add success that is to get the lock. and set the [ expired timeout ] time to ensure that after the downtime , it will not deadlock .

After the concrete operation, determine if this operation has timed out. If the timeout is not removed, the lock is removed if the timeout is not timed out.

Pseudo code:

1          if (MC. ADD ("Lockkey", "Value", ExpiredTime))
 2             {
 3                 //Get lock
 4                 try
 5                 {
 6                     //do Business  function
 7 
 8                     //Check timeout
 9                     if (! Checkedtimeout ())
a                         MC. Delete ("Lockkey");                 catch (Exception e) in                     MC. Delete ("Lockkey");
{                 }             

Redis Distributed Locks

Redis does not have the add command, but there is setnx(SET if not eXists) if the given key already exists, then SETNX does not do any action. The setting succeeds and returns 1. Setting failed, returns 0.

The SETNX command cannot set an expiration time, and you need to use the EXPIRE command to set the expiration time.

Pseudo code:

1 2 3 4 5 6 7 8 9 A-list of
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.