当前位置:网站首页>Alibaba Cloud Official Redis Development Specification
Alibaba Cloud Official Redis Development Specification
2022-08-01 12:02:00 【Young,】

See an Alibaba Cloud official in the Alibaba Cloud community Redis 开发规范,He is an Alibaba Cloud database technical expert(Redis方向)写的,I feel that there are many places worth referring to.I have simply improved the layout and content of the original text,这里分享一下.
一、键值设计
1. key 名设计
(1)【建议】: 可读性和可管理性
以业务名(或数据库名)为前缀(防止 key 冲突),用冒号分隔,比如业务名:表名:id
ugc:video:1
(2)【建议】:简洁性
保证语义的前提下,控制 key 的长度,当 key 较多时,内存占用也不容忽视,例如:
user:{uid}:friends:messages:{mid}简化为u:{uid}:fr:m:{mid}.
(3)【强制】:不要包含特殊字符
反例:包含空格、换行、单双引号以及其他转义字符
2. value 设计
(1)【强制】:拒绝 bigkey(防止网卡流量、慢查询)
string 类型控制在 10KB 以内,hash、list、set、zset 元素个数不要超过 5000.
反例:一个包含 200 万个元素的 list.
非字符串的 bigkey,不要使用 del 删除,使用 hscan、sscan、zscan 方式渐进式删除,同时要注意防止 bigkey 过期时间自动删除问题(例如一个 200 万的 zset 设置 1 小时过期,会触发 del 操作,造成阻塞,而且该操作不会不出现在慢查询中(latency 可查)),查找方法[1]和删除方法[2] .
(2)【推荐】:选择适合的数据类型.
例如:实体类型(要合理控制和使用数据结构内存编码优化配置,例如 ziplist,但也要注意节省内存和性能之间的平衡)
反例:
set user:1:name tom
set user:1:age 19
set user:1:favor football
正例:
hmset user:1 name tom age 19 favor football
3.【推荐】:控制 key 的生命周期,redis 不是垃圾桶.
建议使用 expire 设置过期时间(条件允许可以打散过期时间,防止集中过期),不过期的数据重点关注 idletime.
二、命令使用
1.【推荐】 O(N)命令关注 N 的数量
例如 hgetall、lrange、smembers、zrange、sinter 等并非不能使用,但是需要明确 N 的值.有遍历的需求可以使用 hscan、sscan、zscan 代替.
2.【推荐】:禁用命令
禁止线上使用 keys、flushall、flushdb 等,通过 redis 的 rename 机制禁掉命令,或者使用 scan 的方式渐进式处理.
3.【推荐】合理使用 select
redis 的多数据库较弱,使用数字进行区分,很多客户端支持较差,同时多业务用多数据库实际还是单线程处理,会有干扰.
4.【推荐】使用批量操作提高效率
- 原生命令:例如 mget、mset.
- 非原生命令:可以使用 pipeline 提高效率.
但要注意控制一次批量操作的 元素个数(例如 500 以内,实际也和元素字节数有关).
注意两者不同:
- 原生是原子操作,pipeline 是非原子操作.
- pipeline 可以打包不同的命令,原生做不到
- pipeline 需要客户端和服务端同时支持.
5.【建议】Redis 事务功能较弱,不建议过多使用
Redis 的事务功能较弱(不支持回滚),而且集群版本(自研和官方)要求一次事务操作的 key 必须在一个 slot 上(可以使用 hashtag 功能解决)
6.【建议】Redis 集群版本在使用 Lua 上有特殊要求:
- 所有 key 都应该由 KEYS 数组来传递,redis.call/pcall 里面调用的 redis 命令,key 的位置,必须是 KEYS array, 否则直接返回 error,“-ERR bad lua script for redis cluster, all the keys that the script uses should be passed using the KEYS array”
- 所有 key,必须在 1 个 slot 上,否则直接返回 error, “-ERR eval/evalsha command keys must in same slot”
7.【建议】必要情况下使用 monitor 命令时,要注意不要长时间使用.
三、客户端使用
1.【推荐】避免多个应用使用一个 Redis 实例
正例:不相干的业务拆分,公共数据做服务化.
2.【推荐】使用带有连接池的数据库
使用带有连接池的数据库,可以有效控制连接,同时提高效率,标准使用方式:
执行命令如下:
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//具体的命令
jedis.executeCommand()
} catch (Exception e) {
logger.error("op key {} error: " + e.getMessage(), key, e);
} finally {
//注意这里不是关闭连接,在JedisPool模式下,Jedis会被归还给资源池.
if (jedis != null)
jedis.close();
}
下面是 JedisPool 优化方法的文章:
- Jedis 常见异常汇总[3]
- JedisPool 资源池优化[4]
3.【建议】高并发下建议客户端添加熔断功能(例如 netflix hystrix)
在通过 Redis 客户端操作 Redis 中的数据时,We'll add the circuit breaker logic to it.比如,When the node is in a blown state,Returns null directly and transitions between the three states of the fuse,The specific sample code is as follows:
这样,当某一个 Redis 节点出现问题,Redis The circuit breaker in the client will be monitored in real time,And no longer request the problematic ones Redis 节点,Avoid failure of a single node causing an avalanche of the overall system.
4.【推荐】Make sure your login is secure
设置合理的密码,如有必要可以使用 SSL 加密访问(阿里云 Redis 支持)
5.【建议】选择合适的内存淘汰策略
根据自身业务类型,选好 maxmemory-policy(最大内存淘汰策略),设置好过期时间.
默认策略是 volatile-lru,即超过最大内存后,在过期键中使用 lru 算法进行 key 的剔除,保证不过期数据不被删除,但是可能会出现 OOM 问题.
其他策略如下 :
- allkeys-lru:根据 LRU 算法删除键,不管数据有没有设置超时属性,直到腾出足够空间为止.
- allkeys-random:随机删除所有键,直到腾出足够空间为止.
- volatile-random:随机删除过期键,直到腾出足够空间为止.
- volatile-ttl:根据键值对象的 ttl 属性,删除最近将要过期数据.如果没有,回退到 noeviction 策略.
- noeviction:不会剔除任何数据,拒绝所有写入操作并返回客户端错误信息"(error) OOM command not allowed when used memory",此时 Redis 只响应读操作.
四、相关工具
1.【推荐】:数据同步
redis 间数据同步可以使用:redis-port
2.【推荐】:big key 搜索
3.【推荐】:热点 key 寻找
京东开源的 hotkey[5] Support millisecond-level detection of hotspot data,Push to server cluster memory in milliseconds,Greatly reduces heat key Query pressure on the data layer.
五 附录:删除 bigkey
下面操作可以使用 pipeline 加速.
redis 4.0 已经支持 key 的异步删除,欢迎使用.
1. Hash 删除: hscan + hdel
public void delBigHash(String host, int port, String password, String bigHashKey) {
Jedis jedis = new Jedis(host, port);
if (password != null && !"".equals(password)) {
jedis.auth(password);
}
ScanParams scanParams = new ScanParams().count(100);
String cursor = "0";
do {
ScanResult<Entry<String, String>> scanResult = jedis.hscan(bigHashKey, cursor, scanParams);
List<Entry<String, String>> entryList = scanResult.getResult();
if (entryList != null && !entryList.isEmpty()) {
for (Entry<String, String> entry : entryList) {
jedis.hdel(bigHashKey, entry.getKey());
}
}
cursor = scanResult.getStringCursor();
} while (!"0".equals(cursor));
//删除bigkey
jedis.del(bigHashKey);
}
2. List 删除: ltrim
public void delBigList(String host, int port, String password, String bigListKey) {
Jedis jedis = new Jedis(host, port);
if (password != null && !"".equals(password)) {
jedis.auth(password);
}
long llen = jedis.llen(bigListKey);
int counter = 0;
int left = 100;
while (counter < llen) {
//每次从左侧截掉100个
jedis.ltrim(bigListKey, left, llen);
counter += left;
}
//最终删除key
jedis.del(bigListKey);
}
3. Set 删除: sscan + srem
public void delBigSet(String host, int port, String password, String bigSetKey) {
Jedis jedis = new Jedis(host, port);
if (password != null && !"".equals(password)) {
jedis.auth(password);
}
ScanParams scanParams = new ScanParams().count(100);
String cursor = "0";
do {
ScanResult<String> scanResult = jedis.sscan(bigSetKey, cursor, scanParams);
List<String> memberList = scanResult.getResult();
if (memberList != null && !memberList.isEmpty()) {
for (String member : memberList) {
jedis.srem(bigSetKey, member);
}
}
cursor = scanResult.getStringCursor();
} while (!"0".equals(cursor));
//删除bigkey
jedis.del(bigSetKey);
}
4. SortedSet 删除: zscan + zrem
public void delBigZset(String host, int port, String password, String bigZsetKey) {
Jedis jedis = new Jedis(host, port);
if (password != null && !"".equals(password)) {
jedis.auth(password);
}
ScanParams scanParams = new ScanParams().count(100);
String cursor = "0";
do {
ScanResult<Tuple> scanResult = jedis.zscan(bigZsetKey, cursor, scanParams);
List<Tuple> tupleList = scanResult.getResult();
if (tupleList != null && !tupleList.isEmpty()) {
for (Tuple tuple : tupleList) {
jedis.zrem(bigZsetKey, tuple.getElement());
}
}
cursor = scanResult.getStringCursor();
} while (!"0".equals(cursor));
//删除bigkey
jedis.del(bigZsetKey);
}
参考资料
[1]查找方法: https://developer.aliyun.com/article/531067#cc1[2]删除方法: https://developer.aliyun.com/article/531067#cc2[3]Jedis 常见异常汇总: https://yq.aliyun.com/articles/236384?spm=a2c6h.12873639.article-detail.11.753b1feeTX187Q[4]JedisPool 资源池优化: https://yq.aliyun.com/articles/236383?spm=a2c6h.12873639.article-detail.12.753b1feeTX187Q[5]hotkey: https://gitee.com/jd-platform-opensource/hotkey
边栏推荐
- [5 days countdown] to explore the secret behind the great quality promotion, gift waiting for you to take of $one thousand
- OpenHarmony高校技术俱乐部计划发布
- 程序员如何优雅地解决线上问题?
- 冰冰学习笔记:gcc、gdb等工具的使用
- R语言两个时间序列数据的滞后相关性可视化:使用forecast包的ccf函数绘制交叉相关函数,根据可视化结果分析滞后相关性
- R language ggplot2 visualization: use ggpubr package ggscatter function visualization scatterplot, use xscale wasn't entirely specified X axis measurement adjustment function, set the X coordinate for
- 华硕和微星多款产品将升级英特尔Arc A380和A310显卡
- Promise学习(一)Promise是什么?怎么用?回调地狱怎么解决?
- SCHEMA解惑
- Qt get all files in a folder
猜你喜欢

一篇文章,带你详细了解华为认证体系证书(1)

大众碰到点评的一个字体反爬,落地技术也是绝了

LeakCanary如何监听Service、Root View销毁时机?

冰冰学习笔记:gcc、gdb等工具的使用

How to use DevExpress controls to draw flowcharts?After reading this article, you will understand!

蔚来又一新品牌披露:产品价格低于20万

小程序插件如何帮助开发者受益?

数字化转型实践:世界级2B数字化营销的方法框架

How do programmers solve online problems gracefully?

CloudCompare & PCL ICP registration (point to face)
随机推荐
RK3399 platform development series on introduction to (kernel) 1.52, printk function analysis - the function call will be closed
R语言拟合ARIMA模型:使用forecast包中的auto.arima函数自动搜索最佳参数组合、模型阶数(p,d,q)、设置seasonal参数指定在模型中是否包含季节信息
各位大拿,安装Solaris 11.4操作系统,在安装数据库依赖包的时候包这个错,目前无原厂支持,也无安装盘,联网下载后报这个错,请教怎么解决?
基于ArkUI eTS开发的坚果食谱(NutRecipes)
C#/VB.NET 将PPT或PPTX转换为图像
语音聊天app源码——语音聊天派对
如何利用DevExpress控件绘制流程图?看完这篇文章就懂了!
Promise learning (2) An article takes you to quickly understand the common APIs in Promise
C语言实现!20000用4秒计算
Audio and Video Technology Development Weekly | 256
【无标题】
How do programmers solve online problems gracefully?
冰冰学习笔记:gcc、gdb等工具的使用
新一代超安全蜂窝电池, 思皓爱跑上市13.99万元起售
Aeraki Mesh Joins CNCF Cloud Native Panorama
activiti工作流的分页查询避坑
Programmer's self-cultivation
SCHEMA解惑
Complete Raiders of JS Data Type Conversion
Istio Meetup China:全栈服务网格 - Aeraki 助你在 Istio 服务网格中管理任何七层流量