当前位置:网站首页>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
边栏推荐
- CloudCompare&PCL ICP配准(点到面)
- C语言实现!20000用4秒计算
- Promise learning (1) What is Promise?how to use?How to solve callback hell?
- 蔚来又一新品牌披露:产品价格低于20万
- R语言ggplot2可视化:使用ggpubr包的ggscatter函数可视化散点图、使用xscale函数指定X轴坐标轴度量调整方式、设置x轴坐标为scientific使用科学计数法显示坐标值
- How to use DevExpress controls to draw flowcharts?After reading this article, you will understand!
- 这是我见过写得最烂的Controller层代码,没有之一!
- shell--面试题
- 石头科技打造硬核品牌力 持续出海拓展全球市场
- 如何成功通过 CKA 考试?
猜你喜欢
重庆市大力实施智能建造,推动建筑业数字化转型,助力“建造强市”
A new generation of ultra-safe cellular batteries, Sihao Airun goes on sale starting at 139,900 yuan
Pytest电商项目实战(下)
How to use DevExpress controls to draw flowcharts?After reading this article, you will understand!
Process sibling data into tree data
LeakCanary如何监听Service、Root View销毁时机?
表达式引擎在转转平台的实践
leetcode/submatrix element sum
[Open class preview]: Research and application of super-resolution technology in the field of video quality enhancement
将同级数据处理成树形数据
随机推荐
LeakCanary如何监听Service、Root View销毁时机?
【随心笔记】假期快过去了,都干了点什么
MNIST是什么(plist是什么意思)
bat countdown code
【公开课预告】:超分辨率技术在视频画质增强领域的研究与应用
How do programmers solve online problems gracefully?
Tencent Cloud Native: Service Mesh Practice of Areaki Mesh in the 2022 Winter Olympics Video Live Application
leetcode每日一题:字符串压缩
判断JS数据类型的四种方法
[Community Star Selection] Issue 24 August Update Plan | Keep writing, refuse to lie down!More original incentive packages, as well as Huawei WATCH FIT watches!
Promise学习(四)异步编程的终极解决方案async + await:用同步的方式去写异步代码
Data frame and remote frame of CAN communication
Beyond Compare 4 试用期到期
Promise to learn several key questions (3) the Promise - state change, execution sequence and mechanism, multitasking series, abnormal penetration, interrupt the chain of Promise
[5 days countdown] to explore the secret behind the great quality promotion, gift waiting for you to take of $one thousand
【Unity3D插件】AVPro Video插件分享《视频播放插件》
CloudCompare&PCL ICP配准(点到面)
监视网络连接的ss命令
.NET analyzes the LINQ framework in depth (three: the elegant prelude of LINQ)
STM32 CAN过滤器配置详解