【翻译】Redis SET (分布式锁设计可以参考此文档)

Set key to hold the string value.

设置key保存字符串value

If key already holds a value, it is overwritten, regardless of its type.

如果key已经存贮一个值,那么值将被覆盖,忽略之前的类型。

Any previous time to live associated with the key is discarded on successful SET operation.

之前的与之关联的存活时间,在set成功之后,将被丢弃。

Options

选项

Starting with Redis 2.6.12 SET supports a set of options that modify its

自Redis 2.6.12 版本起 SET 命令支持一组修订的选项。

behavior:

行为

  • EX seconds -- Set the specified expire time, in seconds.
  • EX --设置指定的过期时间以秒为单位。
  • PX milliseconds -- Set the specified expire time, in milliseconds.
  • PX 毫秒 -- 设置指定的过期时间以毫秒为单位。
  • NX -- Only set the key if it does not already exist.
  • NX -- 只有key不存在值时设置
  • XX -- Only set the key if it already exist.
  • XX -- 只有key存在的时候设置

Note: Since the SET command options can replace SETNX, SETEX, PSETEX, it is possible that in future versions of Redis these three commands will be deprecated and finally removed.

注解:自此SET命令 选项能够取代SETNX, SETEX, PSETEX,在将来的Redis版本这三个命令会被弃用甚至被删除。

@return

@simple-string-reply: OK if SET was executed correctly.

@simple-string-reply: 如果 SET 被正确执行,返回 OK

@nil-reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met.

@nil-reply: 在条件不符合时,返回null

@examples

SET mykey "Hello"
GET mykey

Patterns

Note: The following pattern is discouraged in favor of the Redlock algorithm which is only a bit more complex to implement, but offers better guarantees and is fault tolerant.

The command SET resource-name anystring NX EX max-lock-time is a simple way to implement a locking system with Redis.

A client can acquire the lock if the above command returns OK (or retry after some time if the command returns Nil), and remove the lock just using DEL.

一个客户端能获得锁如果上面的命令返回OK (或者尝试多次后这个命令返回null),且用 DEL 命令去删除锁

The lock will be auto-released after the expire time is reached.

锁会在达到过期时间的时自动释放。

It is possible to make this system more robust modifying the unlock schema as follows:

尽可能的让系统更加健壮,修改解锁模式如下:

  • Instead of setting a fixed string, set a non-guessable large random string, called token.

  • 不是设置一个固定的字符串,而是用一个随机的字符串,叫做token

  • Instead of releasing the lock with DEL, send a script that only removes the key if the value matches.

  • 不是用DEL命令释放锁,而是执行一个脚本,如果值匹配的时候,把key删除。

This avoids that a client will try to release the lock after the expire time deleting the key created by another client that acquired the lock later.

这是避免一个客户端在设置的锁过期之后尝试释放锁,删除另外一个客户端设置的锁。

An example of unlock script would be similar to the following:

if redis.call("get",KEYS[1]) == ARGV[1]
then
    return redis.call("del",KEYS[1])
else
    return 0
end

The script should be called with EVAL ...script... 1 resource-name token-value

猜你喜欢

转载自www.cnblogs.com/seeseabky/p/10374133.html