首页 > 数据库 >002-Redis的 String 使用

002-Redis的 String 使用

时间:2022-10-03 18:12:59浏览次数:71  
标签:127.0 String 6379 0.1 Redis value 002 key string

Redis命令十分丰富,包括的命令组有Cluster、Connection、Geo、Hashes、HyperLogLog、Keys、Lists、Pub/Sub、Scripting、Server、Sets、Sorted Sets、Strings、Transactions一共14个redis命令组两百多个redis命令。

1. String

在前面的学习中,我们知道 Redis 的 Value 包含5中类型,String 是其中之一。

# 1. 查看 String 命令组帮助信息
help @String

APPEND key value
summary: Append a value to a key
since: 2.0.0

DECR key
summary: Decrement the integer value of a key by one
since: 1.0.0

DECRBY key decrement
summary: Decrement the integer value of a key by the given number
since: 1.0.0

GET key
summary: Get the value of a key
since: 1.0.0

GETDEL key
summary: Get the value of a key and delete the key
since: 6.2.0

GETEX key [EX seconds|PX milliseconds|EXAT unix-time-seconds|PXAT unix-time-milliseconds|PERSIST]
summary: Get the value of a key and optionally set its expiration
since: 6.2.0

GETRANGE key start end
summary: Get a substring of the string stored at a key
since: 2.4.0

GETSET key value
summary: Set the string value of a key and return its old value
since: 1.0.0

INCR key
summary: Increment the integer value of a key by one
since: 1.0.0

INCRBY key increment
summary: Increment the integer value of a key by the given amount
since: 1.0.0

INCRBYFLOAT key increment
summary: Increment the float value of a key by the given amount
since: 2.6.0

LCS key1 key2 [LEN] [IDX] [MINMATCHLEN len] [WITHMATCHLEN]
summary: Find longest common substring
since: 7.0.0

MGET key [key ...]
summary: Get the values of all the given keys
since: 1.0.0

MSET key value [key value ...]
summary: Set multiple keys to multiple values
since: 1.0.1

MSETNX key value [key value ...]
summary: Set multiple keys to multiple values, only if none of the keys exist
since: 1.0.1

PSETEX key milliseconds value
summary: Set the value and expiration in milliseconds of a key
since: 2.6.0

SET key value [NX|XX] [GET] [EX seconds|PX milliseconds|EXAT unix-time-seconds|PXAT unix-time-milliseconds|KEEPTTL]
summary: Set the string value of a key
since: 1.0.0

SETEX key seconds value
summary: Set the value and expiration of a key
since: 2.0.0

SETNX key value
summary: Set the value of a key, only if the key does not exist
since: 1.0.0

SETRANGE key offset value
summary: Overwrite part of a string at key starting at the specified offset
since: 2.2.0

STRLEN key
summary: Get the length of the value stored in a key
since: 2.2.0

SUBSTR key start end
summary: Get a substring of the string stored at a key
since: 1.0.0

逐一学习以上命令。

1.1 set & get

1.1.1 基本信息

SET key value [NX|XX] [GET] [EX seconds|PX milliseconds|EXAT unix-time-seconds|PXAT unix-time-milliseconds|KEEPTTL]

summary: Set the string value of a key

since: 1.0.0

GET key

summary: Get the value of a key

since: 1.0.0

  • set 命令,用于对一个 key 设置它的 String 类型的 value。
  • get 命令,用于获取一个 key 对应的 value 值。

让我们看一看官网对 set 命令的介绍:

Set key to hold the string value. 为键 key 绑定一个“字符串”类型的值。

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命令执行成功后,之前设置的过期时间都会失效。

127.0.0.1:6379> set key1 "ooxx"
OK

127.0.0.1:6379> get key1
"ooxx"

127.0.0.1:6379> set key1 11
OK

127.0.0.1:6379> get key1
"11"

1.1.2 选项

对于 set 命令,redis 提供了一系列选项:

  • EX seconds – Set the specified expire time, in seconds.

    • 设置键 key 的过期时间,单位秒
  • PX milliseconds – Set the specified expire time, in milliseconds.

    • 设置键 key 的过期时间,单位毫秒
  • EXAT timestamp-seconds -- Set the specified Unix time at which the key will expire, in seconds.

    • 设置键 key 的 Unix 过期时间,单位秒
  • PXAT timestamp-milliseconds -- Set the specified Unix time at which the key will expire, in milliseconds.

    • 设置键 key 的 Unix 过期时间,单位毫秒
  • NX – Only set the key if it does not already exist.

    • 只有键 key 不存在的时候才会设置 key 的值
  • XX – Only set the key if it already exist.

    • 只有键 key 存在的时候才会设置 key 的值
  • KEEPTTL -- Retain the time to live associated with the key.

    • 维持与 key 相关的生存时间
  • GET -- Return the old string stored at key, or nil if key did not exist. An error is returned and SET aborted if the value stored at key is not a string.

    • 返回 key 存储的旧字符串,如果 key 不存在,返回 nil
    • 如果键上存储的值不是字符串,则返回错误并中止 SET

1.1.3 返回

  • 如果 SET 执行正确,则为 OK。

  • 如果用户指定了 NX 或 XX 选项但未满足条件而未执行 SET 操作,则回复为空(nil)。

  • 如果命令是用 GET 选项发出的,无论是否实际执行了 SET,都会作出如下答复

    • Bulk string reply: 键上存储的旧字符串值
    • nil:密钥不存在

1.1.4 练习

127.0.0.1:6379> set key2 "test" EX 5
OK
127.0.0.1:6379> get key2
"test"
127.0.0.1:6379> get key2
(nil)
127.0.0.1:6379> set key2 "test NX" NX
OK
127.0.0.1:6379> get key2
"test NX"
127.0.0.1:6379> set key2 "test NX2" NX
(nil)
127.0.0.1:6379> set key2 "test XX" XX
OK
127.0.0.1:6379> get key2
"test XX"
127.0.0.1:6379> set key2 "test get" get
"test XX"
127.0.0.1:6379> get key2
"test get"

1.1.5 经典使用 - locking system

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

命令 SET resource-name anystring NX EX max-lock-time 是用 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 (如果返回 Nil,则在一段时间后重试) ,客户机可以获取锁,并且仅使用 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.

    • 不要设置固定的字符串,而是设置一个不可猜测的大型随机字符串,称为标记。
  • 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.

这样可以避免客户端在过期时间过后尝试释放锁,从而删除后来获得锁的另一个客户端创建的key。

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

一个解锁脚本的例子类似于下面这样:

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

使用 EVAL... script... 1 resource-name token-value 调用该脚本

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

1.2 append

1.2.1 基本信息

APPEND key value

summary: Append a value to a key

since: 2.0.0

If key already exists and is a string, this command appends the value at the end of the string. 如果 key 已经存在并且是字符串,则此命令将该值追加到字符串的末尾。

If key does not exist it is created and set as an empty string, so APPEND will be similar to SET in this special case. 如果 key 不存在,则创建它并将其设置为空字符串,因此 APPEND 在这种特殊情况下类似于 SET。

1.2.2 返回

  • 追加操作后字符串的长度。

1.2.3 练习

127.0.0.1:6379> keys *
(empty array)
127.0.0.1:6379> append keys "test"
(integer) 4
127.0.0.1:6379> append keys "append"
(integer) 10
127.0.0.1:6379> get keys
"testappend"

1.2.4 经典使用 - Time Series

The APPEND command can be used to create a very compact representation of a list of fixed-size samples, usually referred as time series. Every time a new sample arrives we can store it using the command

APPEND 命令可以用来创建一个非常紧凑的固定大小样本列表,通常称为时间序列。每次新样本到达时,我们都可以使用下面的命令来存储它

append timeseries "fixed-size sample"

Accessing individual elements in the time series is not hard:

访问时间序列中的单个元素并不困难:

  • STRLEN can be used in order to obtain the number of samples.

    • STRLEN 可以用来获得样本的数量。
  • GETRANGE allows for random access of elements. If our time series have associated time information we can easily implement a binary search to get range combining GETRANGE with the Lua scripting engine available in Redis 2.6.

    • GETRANGE 允许随机访问元素。如果我们的时间序列有相关的时间信息,我们可以很容易地实现二进制搜索,以获得结合 GETRANGE 和 Redis 2.6中提供的 Lua 脚本引擎的范围。
  • SETRANGE can be used to overwrite an existing time series.

    • SETRANGE 可用于覆盖现有的时间序列。

The limitation of this pattern is that we are forced into an append-only mode of operation, there is no way to cut the time series to a given size easily because Redis currently lacks a command able to trim string objects. However the space efficiency of time series stored in this way is remarkable.

这种模式的局限性在于,我们被迫采用仅追加的操作模式,没有办法轻松地将时间序列切割到给定的大小,因为 Redis 目前缺乏能够修剪字符串对象的命令。然而,这种方法存储的时间序列的空间效率是显著的。

Hint:

it is possible to switch to a different key based on the current Unix time, in this way it is possible to have just a relatively small amount of samples per key, to avoid dealing with very big keys, and to make this pattern more friendly to be distributed across many Redis instances.

可以根据当前的 Unix 时间切换到一个不同的键,这样每个键可能只有相对较少的样本,以避免处理非常大的键,并使这种模式更友好地分布在许多 Redis 实例中。

An example sampling the temperature of a sensor using fixed-size strings (using a binary format is better in real implementations).

使用固定大小的字符串对传感器的温度进行采样的示例(在实际实现中,使用二进制格式更好)。

127.0.0.1:6379> append ts "0043"
(integer) 4
127.0.0.1:6379> append ts "0035"
(integer) 8
127.0.0.1:6379> append ts "0028"
(integer) 12
127.0.0.1:6379> append ts "0036"
(integer) 16
127.0.0.1:6379> getrange ts 0 3
"0043"
127.0.0.1:6379> getrange ts 4 7
"0035"
127.0.0.1:6379> getrange ts 8 11
"0028"

1.3 incr

1.3.1 基本信息

INCR key

summary: Increment the integer value of a key by one

since: 1.0.0

Increments the number stored at key by one. 将键上存储的数字增加1。

If the key does not exist, it is set to 0 before performing the operation. 如果键不存在,则在执行操作之前将其设置为0。

An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. 如果键包含错误类型的值或包含不能表示为整数的字符串,则返回 Error。

This operation is limited to 64 bit signed integers. 此操作仅限于64位有符号整数。

Note:

  • this is a string operation because Redis does not have a dedicated integer type. The string stored at the key is interpreted as a base-10 64 bit signed integer to execute the operation.

这是一个字符串操作,因为 Redis 没有专用的整数类型。存储在键上的字符串被解释为一个基数为10的64位有符号整数,以执行该操作。

  • Redis stores integers in their integer representation, so for string values that actually hold an integer, there is no overhead for storing the string representation of the integer.

Redis 以整数表示形式存储整数,因此对于实际存储整数的字符串值,存储整数的字符串表示形式没有开销。

1.3.2 返回

  • 增量后键的值

1.3.3 练习

127.0.0.1:6379> set key1 "10"
OK
127.0.0.1:6379> incr key1
(integer) 11
127.0.0.1:6379> get key1
"11"
127.0.0.1:6379> incr key2
(integer) 1
127.0.0.1:6379> get key2
"1"

1.3.4 经典使用 - Counter

The counter pattern is the most obvious thing you can do with Redis atomic increment operations. The idea is simply send an INCR command to Redis every time an operation occurs. For instance in a web application we may want to know how many page views this user did every day of the year.

计数器模式是使用 Redis 原子增量操作可以做的最明显的事情。这个想法是简单地发送一个 INCR 命令到 Redis 每次操作发生。例如,在一个 Web 应用程序中,我们可能想知道这个用户一年中每天浏览了多少页面。

To do so the web application may simply increment a key every time the user performs a page view, creating the key name concatenating the User ID and a string representing the current date.

为此,Web 应用程序可以在用户每次执行页面视图时简单地递增一个键,创建连接 User ID 和表示当前日期的字符串的键名。

This simple pattern can be extended in many ways:

这个简单的模式可以以多种方式扩展:

  • It is possible to use INCR and EXPIRE together at every page view to have a counter counting only the latest N page views separated by less than the specified amount of seconds.

    • 可以在每个页面视图中同时使用 INCR 和 EXPIRE,使计数器只计算最新的 N 个页面视图,两者之间的间隔小于指定的秒数。
  • A client may use GETSET in order to atomically get the current counter value and reset it to zero.

    • 客户端可以使用 GETSET 来自动获取当前计数器值并将其重置为零。
  • Using other atomic increment/decrement commands like DECR or INCRBY it is possible to handle values that may get bigger or smaller depending on the operations performed by the user. Imagine for instance the score of different users in an online game.

    • 使用其他原子增量/减量命令,如 DECR 或 INCRBY,可以根据用户执行的操作处理可能变大或变小的值。例如,想象一下在线游戏中不同用户的得分。
127.0.0.1:6379> incr user01-0929
(integer) 1
127.0.0.1:6379> incr user01-0929
(integer) 2
127.0.0.1:6379> incr user01-0929
(integer) 3
127.0.0.1:6379> incr user01-0929
(integer) 4
127.0.0.1:6379> get user01-0929
"4"

1.3.5 经典使用 - Rate limiter

The rate limiter pattern is a special counter that is used to limit the rate at which an operation can be performed. The classical materialization of this pattern involves limiting the number of requests that can be performed against a public API.

速率限制器模式是一种特殊的计数器,用于限制可以执行操作的速率。这种模式的经典具体化包括限制可以对公共 API 执行的请求数。

We provide two implementations of this pattern using INCR, where we assume that the problem to solve is limiting the number of API calls to a maximum of ten requests per second per IP address.

使用 INCR 提供了此模式的两个实现,假设要解决的问题是将每个 IP 地址每秒的 API 调用数量限制为最多10个请求。

1.3.5.1 Rate limiter1

FUNCTION LIMIT_API_CALL(ip):
ts = CURRENT_UNIX_TIME()
keyname = ip + ":" + ts
MULTI
		INCR(keyname)
		EXPIRE(keyname,10)
EXEC
current = RESPONSE_OF_INCR_WITHIN_MULTI
IF current > 10 THEN
		ERROR "too many requests per second"
ELSE
		PERFORM_API_CALL()
END

Basically we have a counter for every IP, for every different second. But this counters are always incremented setting an expire of 10 seconds so that they'll be removed by Redis automatically when the current second is a different one.

基本上,我们有一个计数器为每个 IP、每秒,但是这个计数器总是递增设置为10秒的过期时间,这样当当前秒数不同时 Redis 就会自动删除它们。

Note the used of MULTI and EXEC in order to make sure that we'll both increment and set the expire at every API call.

注意 MULTI 和 EXEC 的使用,以确保在每次 API 调用时都增加和设置过期。

1.3.5.2 Rate limiter2

FUNCTION LIMIT_API_CALL(ip):
current = GET(ip)
IF current != NULL AND current > 10 THEN
    ERROR "too many requests per second"
ELSE
    value = INCR(ip)
    IF value == 1 THEN
        EXPIRE(ip,1)
    END
    PERFORM_API_CALL()
END

The counter is created in a way that it only will survive one second, starting from the first request performed in the current second. If there are more than 10 requests in the same second the counter will reach a value greater than 10, otherwise it will expire and start again from 0.

从当前秒中执行的第一个请求开始,计数器的创建方式使其只能存活一秒。如果在同一秒内有超过10个请求,计数器将达到一个大于10的值,否则它将过期并从0重新开始。

In the above code there is a race condition. If for some reason the client performs the INCR command but does not perform the EXPIRE the key will be leaked until we'll see the same IP address again.

在上面的代码中有一个竞态条件。如果由于某种原因,客户端执行 INCR 命令,但不执行 EXPIRE ,键将被泄露,直到我们再次看到相同的 IP 地址。

This can be fixed easily turning the INCR with optional EXPIRE into a Lua script that is send using the EVAL command (only available since Redis version 2.6).

这个问题可以很容易地解决,将带有可选 EXPIRE 的 INCR 转换为使用 EVAL 命令发送的 Lua 脚本(仅在 Redis 2.6版本之后可用)。

local current
current = redis.call("incr",KEYS[1])
if current == 1 then
    redis.call("expire",KEYS[1],1)
end

There is a different way to fix this issue without using scripting, by using Redis lists instead of counters. The implementation is more complex and uses more advanced features but has the advantage of remembering the IP addresses of the clients currently performing an API call, that may be useful or not depending on the application.

还有一种不使用脚本的方法来解决这个问题,即使用 Redis 列表而不是计数器。该实现更加复杂,并且使用了更高级的特性,但是它的优点是可以记住当前执行 API 调用的客户机的 IP 地址,这可能有用,取决于应用程序。

FUNCTION LIMIT_API_CALL(ip)
current = LLEN(ip)
IF current > 10 THEN
    ERROR "too many requests per second"
ELSE
    IF EXISTS(ip) == FALSE
        MULTI
            RPUSH(ip,ip)
            EXPIRE(ip,1)
        EXEC
    ELSE
        RPUSHX(ip,ip)
    END
    PERFORM_API_CALL()
END

The RPUSHX command only pushes the element if the key already exists.

RPUSHX 命令仅在键已经存在时才推送元素。

Note that we have a race here, but it is not a problem: EXISTS may return false but the key may be created by another client before we create it inside the MULTI / EXEC block. However this race will just miss an API call under rare conditions, so the rate limiting will still work correctly.

请注意,EXISTS 可能返回 false,但是在 MULTI/EXEC 块中创建它之前,键可能由另一个客户机创建。然而,这将只是错过一个 API 调用在罕见的情况下,所以速率限制将仍然正常工作。

1.4 decr

1.4.1 基本信息

DECR key

summary: Decrement the integer value of a key by one

since: 1.0.0

Decrements the number stored at key by one. 将键存储的数字值减1。

If the key does not exist, it is set to 0 before performing the operation. 如果键不存在,则在执行操作之前将其设置为0。

An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. 如果键包含错误类型的值或包含不能表示为整数的字符串,则返回错误。

This operation is limited to 64 bit signed integers. 此操作仅限于64位有符号整数。

1.4.2 返回

  • 递减后键的值

1.4.3 练习

127.0.0.1:6379> set key3 "111"
OK
127.0.0.1:6379> decr key3
(integer) 110
127.0.0.1:6379> decr key4
(integer) -1

1.5 incrby

1.5.1 基本信息

INCRBY key increment

summary: Increment the integer value of a key by the given amount

since: 1.0.0

Increments the number stored at key by increment. 以增量的方式增加存储在键上的数字。

If the key does not exist, it is set to 0 before performing the operation. 如果键不存在,则在执行操作之前将其设置为0。

An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. 如果键包含错误类型的值或包含不能表示为整数的字符串,则返回错误。

This operation is limited to 64 bit signed integers. 此操作仅限于64位有符号整数。

1.5.2 返回

  • 增量后键的值

1.5.3 练习

127.0.0.1:6379> incrby key3 6
(integer) 116
127.0.0.1:6379> get key3
"116"

1.6 decrby

1.6.1 基本信息

DECRBY key decrement

summary: Decrement the integer value of a key by the given number

since: 1.0.0

Decrements the number stored at key by decrement. 用递减法递减存储在键上的数字。

If the key does not exist, it is set to 0 before performing the operation. 如果键不存在,则在执行操作之前将其设置为0。

An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. 如果键包含错误类型的值或包含不能表示为整数的字符串,则返回错误。

This operation is limited to 64 bit signed integers. 此操作仅限于64位有符号整数。

1.6.2 返回

  • 递减后键的值

1.6.3 练习

127.0.0.1:6379> decrby key3 10
(integer) 106
127.0.0.1:6379> get key3
"106"

1.7 incrbyfloat

1.7.1 基本信息

INCRBYFLOAT key increment

summary: Increment the float value of a key by the given amount

since: 2.6.0

Increment the string representing a floating point number stored at key by the specified increment. 按指定的增量递增表示键存储的浮点数的字符串。

By using a negative increment value, the result is that the value stored at the key is decremented (by the obvious properties of addition). 通过使用负增量值,减少键存储的值。

If the key does not exist, it is set to 0 before performing the operation. 如果键不存在,则在执行操作之前将其设置为0。

An error is returned if one of the following conditions occur:

如果出现下列情况之一,则返回错误:

  • The key contains a value of the wrong type (not a string). 键包含错误类型的值(不是字符串)。
  • The current key content or the specified increment are not parsable as a double precision floating point number. 当前键内容或指定的增量不能解析为双精度浮点数。

If the command is successful the new incremented value is stored as the new value of the key (replacing the old one), and returned to the caller as a string.

如果命令成功,新的递增值将作为键的新值存储(替换旧值) ,并作为字符串返回给调用者。

Both the value already contained in the string key and the increment argument can be optionally provided in exponential notation, however the value computed after the increment is stored consistently in the same format, that is, an integer number followed (if needed) by a dot, and a variable number of digits representing the decimal part of the number. Trailing zeroes are always removed.

字符串键中已经包含的值和增量参数都可以选择性地以指数形式提供,但是在增量之后计算的值以相同的格式一致地存储,也就是说,一个整数数字(如果需要的话)后面跟一个点,以及一个表示该数字的小数部分的可变数位数。尾随的零总是被删除。

The precision of the output is fixed at 17 digits after the decimal point regardless of the actual internal precision of the computation.

无论计算的实际内部精度如何,输出精度固定在小数点后17位。

1.7.2 返回

  • 递增后的 key 的值

1.7.3 练习

127.0.0.1:6379> incrbyfloat key3 2.33
"108.33"
127.0.0.1:6379> get key3
"108.33"
127.0.0.1:6379> incrbyfloat key4 1
"0"
127.0.0.1:6379> get key4
"0"
127.0.0.1:6379> incrbyfloat key4 1.00
"1"
127.0.0.1:6379> get key4
"1"

1.8 getdel

1.8.1 基本信息

GETDEL key

summary: Get the value of a key and delete the key

since: 6.2.0

Get the value of key and delete the key. 获取键的值并删除该键。

This command is similar to GET, except for the fact that it also deletes the key on success (if and only if the key's value type is a string). 这个命令类似于 GET,除了它在成功时会删除键(当且仅当键的值类型是字符串时)。

1.8.2 返回

  • key 的值
  • 如果 key 不存在,则为 nil
  • 如果 key 的值类型不是字符串,则为错误

1.8.3 练习

127.0.0.1:6379> set key5 "test getdel"
OK
127.0.0.1:6379> get key5
"test getdel"
127.0.0.1:6379> getdel key5
"test getdel"
127.0.0.1:6379> get key5
(nil)

1.9 getex

1.9.1 基本信息

GETEX key [EX seconds|PX milliseconds|EXAT unix-time-seconds|PXAT unix-time-milliseconds|PERSIST]

summary: Get the value of a key and optionally set its expiration

since: 6.2.0

Get the value of key and optionally set its expiration. 获取 key 的值并可选地设置其过期时间。

GETEX is similar to GET, but is a write command with additional options. GETEX 类似于 GET,但是是一个带有附加选项的 write 命令。

1.9.2 选项

  • EX seconds -- Set the specified expire time, in seconds.

    • EX 秒——设置指定的过期时间(以秒为单位)。
  • PX milliseconds -- Set the specified expire time, in milliseconds.

    • PX 毫秒——设置指定的过期时间(以毫秒为单位)。
  • EXAT timestamp-seconds -- Set the specified Unix time at which the key will expire, in seconds.

    • EXAT 时间戳-秒——设置指定的过期 Unix 时间(以秒为单位)。
  • PXAT timestamp-milliseconds -- Set the specified Unix time at which the key will expire, in milliseconds.

    • PXAT 时间戳-毫秒——设置指定的过期时间 Unix 时间,单位为毫秒。
  • PERSIST -- Remove the time to live associated with the key.

    • PERSIST ——删除键的生存时间。

1.9.3 返回

  • key 的值
  • 如果 key 不存在,则为 nil

1.9.4 练习

127.0.0.1:6379> set key6 "test getex"
OK
127.0.0.1:6379> ttl key6
(integer) -1
127.0.0.1:6379> getex key6 ex 6
"test getex"
127.0.0.1:6379> ttl key6
(integer) 3
127.0.0.1:6379> get key6
(nil)

1.10 getrange

1.10.1 基本信息

GETRANGE key start end

summary: Get a substring of the string stored at a key

since: 2.4.0

Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive). 返回存储在 key 处的字符串值的子字符串,该子字符串由偏移量开始和结束(两者都包含在内)确定。

Negative offsets can be used in order to provide an offset starting from the end of the string. So -1 means the last character, -2 the penultimate and so forth. 可以使用负偏移量来提供从字符串末尾开始的偏移量,-1表示最后一个字符,-2表示倒数第二个字符,依此类推。

The function handles out of range requests by limiting the resulting range to the actual length of the string. 函数通过将结果范围限制为字符串的实际长度来处理超出范围的请求。

1.10.2 返回

  • 截取出的字符串

1.10.3 练习

127.0.0.1:6379> set ket8 "hello redis"
OK
127.0.0.1:6379> getrange ket8 2 4
"llo"

1.11 mget

1.11.1 基本信息

MGET key [key ...]

summary: Get the values of all the given keys

since: 1.0.0

Returns the values of all specified keys. 返回所有指定键的值。

For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails. 对于每个不包含字符串值或不存在的键,将返回特殊值 nil。

1.11.2 返回

  • 指定键的值列表

1.11.3 练习

127.0.0.1:6379> mget key1 key2 key3
1) "key1"
2) "key2"
3) "key3"

1.12 mset

1.12.1 基本信息

MSET key value [key value ...]

summary: Set multiple keys to multiple values

since: 1.0.1

Sets the given keys to their respective values. 将给定的键设置为它们各自的值。

MSET replaces existing values with new values, just as regular SET. See MSETNX if you don't want to overwrite existing values.

MSET 用新值替换现有值,就像普通的 SET 一样。如果不想覆盖现有值,请参见 MSETNX。

MSET is atomic, so all given keys are set at once. It is not possible for clients to see that some of the keys were updated while others are unchanged.

MSET 是原子的,因此所有给定的键都是一次性设置的。客户端不可能看到一些键被更新,而其他键没有变化。

1.12.2 返回

  • 总是 OK,因为 MSET 不会失败。

1.12.3 练习

127.0.0.1:6379> mset key1 "key111" key2 "key222" key3 "key333"
OK
127.0.0.1:6379> mget key1 key2 key3
1) "key111"
2) "key222"
3) "key333"

1.13 msetnx

1.13.1 基本信息

MSETNX key value [key value ...]

summary: Set multiple keys to multiple values, only if none of the keys exist

since: 1.0.1

Sets the given keys to their respective values. 将给定的键设置为它们各自的值。

MSETNX will not perform any operation at all even if just a single key already exists。 即使只有一个键已经存在,MSETNX 也不会执行任何操作。

Because of this semantic MSETNX can be used in order to set different keys representing different fields of a unique logic object in a way that ensures that either all the fields or none at all are set.

由于这种语义,可以使用 MSETNX 来设置表示唯一逻辑对象的不同字段的不同键,从而确保设置了所有字段或根本没有字段。
MSETNX is atomic, so all given keys are set at once. It is not possible for clients to see that some of the keys were updated while others are unchanged.

MSETNX 是原子的,因此所有给定的键都是一次性设置的。客户端不可能看到一些键被更新,而其他键没有变化。

1.13.2 返回

  • 1:所有的键都设置好了
  • 0:没有设置键(至少已经存在一个键)

1.13.3 练习

127.0.0.1:6379> msetnx key1 "test11111" key4 "test4" key5 "test55"
(integer) 0

1.14 psetex

1.14.1 基本信息

PSETEX key milliseconds value

summary: Set the value and expiration in milliseconds of a key

since: 2.6.0

PSETEX works exactly like SETEX with the sole difference that the expire time is specified in milliseconds instead of seconds.

PSETEX 的工作原理与 SETEX 完全相同,唯一的区别是过期时间是以毫秒而不是以秒为单位指定的。

1.14.2 返回

  • OK

1.14.3 练习

127.0.0.1:6379> psetex key7 1000 "tet"
OK
127.0.0.1:6379> get key7
(nil)

1.15 setrange

1.15.1 基本信息

SETRANGE key offset value

summary: Overwrite part of a string at key starting at the specified offset

since: 2.2.0

Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. 覆盖存储在键上的字符串的一部分,从指定的偏移量开始,覆盖整个值长度。

If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. 如果偏移量大于键处字符串的当前长度,则使用零字节填充该字符串以使偏移量适合。

Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset. 不存在的键被认为是空字符串,因此这个命令将确保它包含一个足够大的字符串,以便能够设置偏移量的值。

Note :

the maximum offset that you can set is 2^29 -1 (536870911), as Redis Strings are limited to 512 megabytes. If you need to grow beyond this size, you can use multiple keys. 可以设置的最大偏移量为2 ^ 29 -1(536870911) ,因为 Redis String 限制为512兆字节。如果需要扩展到超过这个大小,可以使用多个键。

1.15.2 返回

  • 字符串被命令修改后的长度。

1.15.3 练习

127.0.0.1:6379> get key3
"key333"
127.0.0.1:6379> setrange key3 2 "setrange"
(integer) 10
127.0.0.1:6379> get key3
"kesetrange"

1.16 strlen

1.16.1 基本信息

STRLEN key

summary: Get the length of the value stored in a key

since: 2.2.0

Returns the length of the string value stored at key. 返回存储在 key 中的字符串值的长度。

An error is returned when key holds a non-string value. 如果 key 包含非字符串值,则返回错误。

1.16.2 返回

  • 键的字符串的长度
  • 键不存在时为0

1.16.3 练习

127.0.0.1:6379> strlen key3
(integer) 10

标签:127.0,String,6379,0.1,Redis,value,002,key,string
From: https://www.cnblogs.com/autumncat/p/16750913.html

相关文章

  • redis 允许远程访问
    1.取消绑定本地地址找到redis配置文件,redis.conf,注释掉指定的bind,当不指定时表示允许所有访问。   2.关闭保护模式在redis服务器上使用redis-cli,执行命令C......
  • Redis高性能怎么做到的?
    Redis的高性能怎么做到的?Redis这个NOSQL数据库在计算机界可谓是无人不知,无人不晓。只要涉及到数据那么就需要数据库,数据库类型很多,但是NOSQL的kv内存数据库也很多,redis作为......
  • Redis入门(四):springboot整合redis
    案例一​​demo​​​为​​chnx/springboot/redis01​​创建springboot项目,导入redis依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>s......
  • String和StringBuffer的选用
    String的字符串对象是字符串常量池里的,如果需要频繁的连接和改动的话,会导致很多不用的字符串常量被废弃此时,选用StringBuffer效率更高......
  • Redis6
    Redis数据结构redis-cli-hhost-pport-apasswordhost:远程redis服务器hostport:远程redis服务端口password:远程redis服务密码(无密码的的话就不需要-a参数了)......
  • redis 缓存的模式
    一:读1:缓存边缘化(cacheaside)应用程序先读取缓存,如果缓存没有,再去读数据库,然后更新缓存   2:通读(Read-through)在上面的基础上抽象一层缓存层,让缓存层去读缓存数据......
  • Redis详解
    Redis介绍1.Redis是一个基于内存的高性能key-value数据库。是完全开源免费的,用C语言编写的,遵守BSD协议2.Redis特点:1)Redis是基于内存......
  • Redis 缓存穿透, 缓存击穿, 缓存雪崩的解决方案与布隆过滤器
    缓存穿透解决方案设置空值布隆过滤器优点可以将存在的缓存,位置设置为1,然后当不存在的参数过来的时候,会匹配到0上,这样就会直接返回不存在缺点存......
  • Redis的架构演进过程
    Redis架构演进一主二从这也是常用的架构,,MASTER用于写服务,SLAVE提供读服务但是存在弊端,就是主MASTER宕机后,SLAVE无法升级,导致无法提供写服务哨兵监控为了......
  • SpringBoot整合Redis[哨兵版]
    SpringBoot整合Redis[哨兵版]修改配置文件server:port:8080spring:application:name:redisredis:#host:192.168.247.141#port:6379......