来源:yq.aliyun.com/articles/531067redis
做者:付磊-起扬 算法
本文主要介绍在使用阿里云Redis的开发规范,从下面几个方面进行说明。数据库
键值设计数组
命令使用微信
客户端使用数据结构
相关工具并发
经过本文的介绍能够减小使用Redis过程带来的问题。dom
以业务名(或数据库名)为前缀(防止key冲突),用冒号分隔,好比业务名:表名:id异步
ugc:video:1
ide
保证语义的前提下,控制key的长度,当key较多时,内存占用也不容忽视,例如:
user:{uid}:friends:messages:{mid}简化为u:{uid}:fr:m:{mid}。
反例:包含空格、换行、单双引号以及其余转义字符
防止网卡流量、慢查询,string类型控制在10KB之内,hash、list、set、zset元素个数不要超过5000。
反例:一个包含200万个元素的list。
非字符串的bigkey,不要使用del删除,使用hscan、sscan、zscan方式渐进式删除,同时要注意防止bigkey过时时间自动删除问题(例如一个200万的zset设置1小时过时,会触发del操做,形成阻塞,并且该操做不会不出如今慢查询中(latency可查)),查找方法和删除方法
例如:实体类型(要合理控制和使用数据结构内存编码优化配置,例如ziplist,但也要注意节省内存和性能之间的平衡)。了解下,Redis 为何这么快?
反例:
set user:1:name tom
set user:1:age 19
set user:1:favor football
正例:
hmset user:1 name tom age 19 favor football
redis不是垃圾桶,建议使用expire设置过时时间(条件容许能够打散过时时间,防止集中过时),不过时的数据重点关注idletime。
例如hgetall、lrange、smembers、zrange、sinter等并不是不能使用,可是须要明确N的值。有遍历的需求可使用hscan、sscan、zscan代替。
禁止线上使用keys、flushall、flushdb等,经过redis的rename机制禁掉命令,或者使用scan的方式渐进式处理。一个致命的 Redis 命令,致使公司损失 400 万!!关注Java技术栈微信公众号,在后台回复关键字:redis,能够获取更多栈长整理的 Redis 系列技术干货。
redis的多数据库较弱,使用数字进行区分,不少客户端支持较差,同时多业务用多数据库实际仍是单线程处理,会有干扰。
原生命令:例如mget、mset。
非原生命令:可使用pipeline提升效率。
但要注意控制一次批量操做的元素个数(例如500之内,实际也和元素字节数有关)。
注意二者不一样:
原生是原子操做,pipeline是非原子操做。
pipeline能够打包不一样的命令,原生作不到
pipeline须要客户端和服务端同时支持。
Redis的事务功能较弱(不支持回滚),并且集群版本(自研和官方)要求一次事务操做的key必须在一个slot上(可使用hashtag功能解决)。
一、全部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 arrayrn" 二、全部key,必须在1个slot上,不然直接返回error, "-ERR eval/evalsha command keys must in same slotrn"
必要状况下使用monitor命令时,要注意不要长时间使用。
不相干的业务拆分,公共数据作服务化。
能够有效控制链接,同时提升效率,标准使用方式:
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();
}
高并发下建议客户端添加熔断功能(例如netflix hystrix)
设置合理的密码,若有必要可使用SSL加密访问(阿里云Redis支持)
根据自身业务类型,选好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只响应读操做。
redis间数据同步可使用:redis-port
redis大key搜索工具
内部实现使用monitor,因此建议短期使用facebook的redis-faina 阿里云Redis已经在内核层面解决热点key问题
下面操做可使用pipeline加速。
redis 4.0已经支持key的异步删除,欢迎使用。
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);
}
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);
}
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);
}
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);}