Home > Database > Redis > body text

What are the ways to lock redis?

WBOY
Release: 2023-05-27 12:43:06
forward
1428 people have browsed it

The common locking commands of redis are INCR, SETNX, SET

1, INCR

The locking idea of ​​​​this kind of lock is:

key does not exist, then the value of key will be initialized to 0 first, and then the INCR operation will be performed to increase it by one.

Then when other users perform the INCR operation to add one, if the returned value is greater than 1, it means that the key is being locked for use.

1. Client A requests the server to obtain the key value of 1, indicating that the lock has been obtained.

2. Client B also requests the server to obtain the key value of 2, indicating that the lock acquisition failed.

3. Client A completes the execution of the code and deletes the lock

4. Client B waits for a period of time and obtains the key value of 1 when making a request, indicating that the lock is successfully acquired

5. Client B executes the code and deletes the lock

$redis->incr($key);
$redis->expire($key, $ttl); //设置生成时间为1秒
Copy after login

Specific command:

127.0.0.1:6379>INCR keyName
Copy after login

2. SETNX

The idea behind this kind of locking is that if the key If it does not exist, set the key to value. If the key exists, SETNX does not take any action.

SETNX is the abbreviation of SET if Not eXists.

1. Client A requests the server to set the key value. If the setting is successful, it means the lock is successful.

2. Client B also requests the server to set the key value. If If the return fails, it means the locking failed

3. Client A completes the code execution and deletes the lock

4. Client B requests to set the key value after waiting for a period of time. The setting is successful

5. Client B executes the code and deletes the lock

$redis->setNX($key, $value);
$redis->expire($key, $ttl);
Copy after login

The specific command is:

redis> SETNX keyName value
(integer) 1
Copy after login

The setting is successful and 1 is returned; the setting fails and the lock is returned 0

3. SET

The above two methods have a problem. You will find that they need to set the key expiration.

So why do we need to set key expiration?

If the request execution exits unexpectedly for some reason, causing the lock to be created but not deleted, then the lock will always exist, so that the cache will never be updated in the future.

So we need to add an expiration time to the lock to prevent accidents.

But using Expire to set it is not an atomic operation.

So you can also ensure atomicity through transactions, but there are still some problems, so the official cited another one. Using the SET command itself has included the function of setting the expiration time starting from version 2.6.12.

1. Client A requests the server to set the key value. If the setting is successful, the lock is successful.

2. Client B also requests the server to set the key value. If the return fails, Then it means that the lock failed.

3. Client A completes the execution of the code and deletes the lock.

4. Client B waits for a period of time before requesting to set the key value, and the setting is successful

5. Client B executes the code and deletes the lock

$redis->set($key, $value, array('nx', 'ex' => $ttl));  //ex表示秒
Copy after login

Specific usage:

redis>set key value NX EX max-lock-time 实现加锁
Copy after login

Command explanation:

  • key: The key is the key value of redis as the identifier of the lock, and the value is here as the identifier of the client. Only when the key-value match can the right to delete the lock [Ensure security]

  • max-lock-time: Set the expiration time through max-lock-time to ensure that no deadlock will occur [Avoid deadlock]

  • NX: The operation will only be performed when the key does not exist, if not exists;

  • EX: Set the expiration time of the key to Seconds, the specific time is determined by the fifth parameter

## Lock code:

 Jedis jedis = new Jedis("127.0.0.1", 6379);
 private static final String SUCCESS = "OK";
 /**
  * 加锁操作
  * @param key 锁标识
  * @param value 客户端标识
  * @param timeOut 过期时间
  */
  
 public Boolean lock(String key,String value,Long timeOut){
     String var1 = jedis.set(key,value,"NX","EX",timeOut);
     if(LOCK_SUCCESS.equals(var1)){
         return true;
     }
     return false;
 }
Copy after login

Unlock code:

 Jedis jedis = new Jedis("127.0.0.1", 6379); 
 private static final Long UNLOCK_SUCCESS = 1L;
 /**
  * 解锁操作
  * @param key 锁标识
  * @param value 客户端标识
  * @return
  */
  
 public static Boolean unLock(String key,String value){
     String luaScript = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then return 
     redis.call(\"del\",KEYS[1]) else  return 0 end";
     Object var2 = jedis.eval(luaScript,Collections.singletonList(key), Collections.singletonList(value));
     if (UNLOCK_SUCCESS == var2) {
         return true;
     }
     return false;
}
Copy after login
luaScript This string is a lua script, which means that if the value obtained according to the key is the same as the value passed in, execute del, otherwise it will return 0 [guarantee security]

jedis .eval(String,list,list); This command is to execute the lua script. The set of KEYS is the second parameter, and the set of ARGV is the third parameter [atomic operation to ensure unlocking]

The above is achieved How to use redis to correctly implement distributed locks, but there is a small flaw that the lock expiration time should be set to an appropriate value. This actually needs to be considered based on the business scenario.

The above is the detailed content of What are the ways to lock redis?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template