diff --git a/中间件/redis/redis.md b/中间件/redis/redis.md index eea6914..94a9203 100644 --- a/中间件/redis/redis.md +++ b/中间件/redis/redis.md @@ -222,6 +222,8 @@ - [`CLUSTER GETKEYSINSLOT`](#cluster-getkeysinslot) - [MIGRATE](#migrate-1) - [ASK redirection](#ask-redirection) + - [Client connections and redirection handling](#client-connections-and-redirection-handling) + - [CLUSTER SLOTS](#cluster-slots) # redis @@ -3524,4 +3526,54 @@ ASK重定向的语义如下: 一旦关于`slot`的迁移完成,`A`节点后续针对该`slot`的请求将返回`MOVED error`,client将永久的将`slot`映射到`B`节点。 +#### Client connections and redirection handling +为了提高效率,redis cluster clients维护了一个`map of the current slot configuration`。但是,该配置并不需要实时保持最新,当client联系错误的节点时,将会触发重定向,client可以根据重定向来更新其内部slot映射。 + +通常,clients会在如下两种场景来拉取`slots和mapped node addresses`的完整列表: +- 在client启动时,会注入初始的slots配置 +- 当client接收到`MOVED`重定向时(`ASK`重定向并不会触发该行为,因为`ASK`重定向是一次性的) + +在client接收到`MOVED`重定向时,可以`仅对导致重定向的slot`进行更新,但是,该更新方式通常是低效的:通常`slot configuration`是批量被修改的,并不会只修改一个slot。例如replica被提升为master后,所有old master中的slots都需要被重新映射到新master。 + +> 故而,在触发`MOVED`重定向时,直接拉取slots到nodes的所有映射会更加简单。 + +client可以发送`CLUSTER SLOTS`命令来获取`an array of slot ranges and associated master and replica nodes serving the specified ranges`。 + +##### CLUSTER SLOTS +如下示例展示了`CLUSTER SLOTS`命令的使用: +```redis-cli +127.0.0.1:7000> cluster slots +1) 1) (integer) 5461 + 2) (integer) 10922 + 3) 1) "127.0.0.1" + 2) (integer) 7001 + 4) 1) "127.0.0.1" + 2) (integer) 7004 +2) 1) (integer) 0 + 2) (integer) 5460 + 3) 1) "127.0.0.1" + 2) (integer) 7000 + 4) 1) "127.0.0.1" + 2) (integer) 7003 +3) 1) (integer) 10923 + 2) (integer) 16383 + 3) 1) "127.0.0.1" + 2) (integer) 7002 + 4) 1) "127.0.0.1" + 2) (integer) 7005 +``` + +在`CLUSTER SLOTS`返回的数组中, +- 每个元素的`前两个子元素`代表`slot range`的开始位置和结束位置 + - 例如`1)`中的slot range的开始位置为`5461`,结束位置为`10922` +- 每个元素的`其他子元素`代表`address-port` pairs,其中,第一个address-port pair为`master serving the slot`,额外的`address-port pairs`代表`replicas serving the same slot` + - 例如`1)`中指定的slot range中,master为`127.0.0.1:7001`,而replica则是`127.0.0.1:7004` +- Replicas will be listed only when not in an error condition + +如果cluster的配置有误,`CLUSTER SLOTS`并不保证返回的范围会覆盖所有`16384`个slots。对于该种场景,clients在初始化`slots configuration map`时,会将`未分配slots`的target node设置为`NULL`,并且当用户尝试访问的key属于这些`unassigned slots`时,会报异常。 + +当slot发现为unassigned时,在向调用方返回异常之前,client会尝试拉取slots configuration,并且校验cluster当前是否被正确配置。 + + +