客户端 #
服务器使用 RESP,所以 Redis 客户端可以直接用——但有三处需要调整:类型不匹配从不报错、scan 游标必须当作不透明值处理、没有 SELECT/MULTI。
redis-cli #
redis-cli -h 127.0.0.1 -p 11001
# with TLS and auth
redis-cli --tls --cacert ./ca.crt -a "$ICEFIREDB_AUTH" -h db1.internal -p 11001
SET user:1 '{"name":"ada"}' EX 300
HGETALL user:1
SCAN 0 MATCH 'user:*' COUNT 100
XSCAN HASH "" MATCH '^user:' COUNT 100
INFO
redis-cli --scan 可用:它从 0 开始,循环到游标重新变成 0 为止。
Go (github.com/redis/go-redis/v9)
#
package main
import (
"context"
"crypto/tls"
"fmt"
"github.com/redis/go-redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:11001",
Password: "", // set when the server runs with --auth
TLSConfig: nil, // &tls.Config{...} when --tls-cert/--tls-key are used
DB: 0, // there is only database 0
})
defer rdb.Close()
if err := rdb.Set(ctx, "user:1", `{"name":"ada"}`, 0).Err(); err != nil {
panic(err)
}
v, err := rdb.Get(ctx, "user:1").Result()
fmt.Println(v, err) // {"name":"ada"} <nil>
fmt.Println(rdb.HSet(ctx, "user:1", "name", "ada").Val()) // 1
// Paginate keys: the cursor is opaque, handle it as a string.
cursor := uint64(0)
for {
keys, next, err := rdb.Scan(ctx, cursor, "user:*", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(keys)
if next == 0 {
break
}
cursor = next
}
}
注意事项——类型化 scan 辅助函数。 rdb.HScan、rdb.SScan、rdb.ZScan 和 rdb.Scan 都会用 strconv.ParseUint 强制转换游标,而 HScan/SScan/ZScan 还额外要求游标是数字。本引擎对这三条命令返回最后一个字段/成员名作为游标,所以这些类型化辅助函数会以解析错误失败。请改用通用 API:
cursor := "0"
for {
vals, err := rdb.Do(ctx, "HSCAN", "user:1", cursor, "MATCH", "n*", "COUNT", 100).Slice()
if err != nil {
panic(err)
}
cursor = fmt.Sprint(vals[0])
pairs := vals[1].([]interface{})
for i := 0; i+1 < len(pairs); i += 2 {
fmt.Println(pairs[i], pairs[i+1])
}
if cursor == "0" || cursor == "" {
break
}
}
redis.NewClusterClient 同样可用:CLUSTER SLOTS 报告主节点上一段覆盖 0-16383 的区间,这是一个合法的单分片拓扑。它对分摊负载毫无意义,对客户端统一性有用——而且它会自动跟随 -MOVED 重定向。
Python (redis-py)
#
import redis
r = redis.Redis(
host="127.0.0.1", port=11001,
password=None, # set when the server runs with --auth
ssl=False, # True with --tls-cert/--tls-key
decode_responses=True,
)
r.set("user:1", '{"name":"ada"}')
print(r.get("user:1"))
print(r.hset("user:1", "name", "ada"))
print(r.ttl("user:1")) # works: TTL is per type
# The typed helpers coerce the cursor to int, which this engine's cursors are not.
cursor = "0"
while True:
cursor, pairs = r.execute_command("HSCAN", "user:1", cursor, "COUNT", 100)
print(pairs)
if cursor in ("0", b"0"):
break
Node (ioredis)
#
const Redis = require("ioredis");
const r = new Redis({ host: "127.0.0.1", port: 11001 /*, password, tls: {} */ });
(async () => {
await r.set("user:1", '{"name":"ada"}');
console.log(await r.get("user:1"));
console.log(await r.hset("user:1", "name", "ada"));
// hscan returns [cursor, flatArray]; ioredis keeps the cursor as a string
let [cursor, flat] = await r.hscan("user:1", "0", "COUNT", 100);
while (cursor !== "0") {
[cursor, flat] = await r.hscan("user:1", cursor, "COUNT", 100);
}
})();
常见注意事项 #
| 注意事项 | 该怎么办 |
|---|---|
没有 WRONGTYPE | 在键命名约定里或应用层强制执行类型规则 |
没有 TYPE 命令 | 自己记录类型;或用 EXISTS/HKEYEXISTS/LKEYEXISTS/SKEYEXISTS 探测 |
没有 SELECT | 设 DB: 0,然后就不用再管它 |
没有 MULTI/EXEC | 用 SET … NX 做原子占位,用 BARRIER 保证读到自己刚写的 |
没有 BLPOP | 轮询 LPOP,或改用为阻塞读设计的队列 |
在 P2P 驱动上,HGET/GET 一个空值会返回 null | 当"空"必须保留时,存一个哨兵值 |
从节点读需要 --openreads | 没有它就只能等 -MOVED 0 <leader> |
INFO 不接受参数 | 解析这一条回复;不要调用 INFO memory |
从客户端做健康检查 #
redis-cli -p 11001 PING # PONG when the process is up
redis-cli -p 11001 BARRIER # OK once this client's writes are applied
redis-cli -p 11001 RAFT LEADER # who to write to
curl -fsS http://127.0.0.1:11002/readyz # 200 "ready" once storage is initialized