redis(REmote DIctionary Server)
是一个基于内存的,key/value
数据库,常用来做缓存。
介绍
Redis 的优点
- 性能极高:Redis 能支持超过 100K+ 每秒的读写频率。
- 丰富的数据类型
- 原子:Redis的所有操作都是原子性的,同时Redis还支持对几个操作全并后的原子性执行。
- 丰富的特性:Redis还支持 publish/subscribe、通知、key 过期等等特性。
- 支持分布式部署
- 支持 rdp、aof 持久化存储
Redis 数据类型
常用数据类型如下:
strings
lists
([]interface{})
sets
(集合,元素不重复)
sorted sets
hashes(hash map)
bitmap
- …
key 命名规则:
- 命名规则:
[a-zA-Z][a-zA-Z0-9_]*
- 层级:使用
:
分隔,如 “app:version”
Redis 协议
- 参考
- Redis
Server
和 Client
使用 TCP 协议通信
- 服务端默认监听在 6379 端口
- Redis 协议在 1.2 时提出,2.0 时成为通信标准
- 服务端和客户端通信时,一律采用
\r\n(CRLF)
结尾
- Redis 协议请求格式
*<参数数量>\r\n
$<参数 1 的字节数量>\r\n
<参数 1 的数据>\r\n
...
$<参数 N 的字节数量>\r\n
<参数 N 的数据>\r\n
请求发送的数据示例:set key1 value1
,原始数据格式:
*3\r\n$3\r\nSET\r\n$4\r\nkey1\r\n$6\r\nvalue1\r\n
换行生效的格式:
*3
$3
SET
$4
key1
$6
value1
- Redis 协议响应格式
- 第一个字节确定回复类型
+
状态回复(status reply)
-
错误回复(error reply)
:
整数回复(integer reply)
$
批量回复(bulk reply)
*
多条批量回复(multi bulk reply)
- 以
\r\n(CRLF)
结尾
上述示例的回复:
+OK\r\n
常见部署模式
缓存的挑战
缓存穿透
缓存和数据库中都没有的数据时,大量请求直接去DB查询数据,导致DB压力增大
缓存击穿
缓存中没有但数据库中有的数据
- 设置热点数据永远不过期
- 过期时间均匀分布
- 接口限流与熔断,降级
- 加互斥锁
缓存雪崩
数据大批量到过期时间,而查询数据量巨大,引起数据库压力过大甚至挂掉
- 缓存数据的过期时间设置随机,防止同一时间大量数据过期现象发生
- 如果缓存数据库是分布式部署,将热点数据均匀分布在不同的缓存数据中
- 缓存污染(或者磁盘满)
- 配置淘汰策略:noeviction、volatile-random、volatile-ttl、volatile-lru、volatile-lfu、allkeys-lru、allkeys-random 和 allkeys-lfu 策略
- 建议把缓存容量设置为总数据量的 15% 到 30%,兼顾访问性能和内存空间开销
CONFIG SET maxmemory 16gb
- 缓存和数据库一致性
client
windows
https://redisdesktop.com/download
Linux
sudo snap install another-redis-desktop-manager
示例
访问链接
redis://[:password]@localhost:6379/1
go
ceilometer 实践
127.0.0.1:6379> SMEMBERS _tooz_groups
1) "central-111"
2) "ceilometer.notification"
3) "alarm_evaluator"
4) "central-global"
127.0.0.1:6379> type _tooz_group:central-111
hash
127.0.0.1:6379> type _tooz_group:ceilometer.notification
hash
127.0.0.1:6379> type _tooz_group:central-global
hash
127.0.0.1:6379> type _tooz_group:alarm_evaluator
hash
127.0.0.1:6379> HGETALL _tooz_group:central-111
1) "__created__"
2) "1"
127.0.0.1:6379> HGETALL _tooz_group:ceilometer.notification
1) "__created__"
2) "1"
3) "32cd6ee7-ab1b-4004-bbf6-224ac93bb2f2"
4) "\xc4\x00"
...
127.0.0.1:6379> HGETALL _tooz_group:central-global
1) "__created__"
2) "1"
127.0.0.1:6379> HGETALL _tooz_group:alarm_evaluator
1) "__created__"
2) "1"
3) "382a6e79-1841-466d-8001-49d603267f07"
4) "\xc4\x00"
...
127.0.0.1:6379>
参考