阿里云Redis開發(fā)規(guī)范
趙客縵胡纓v吳鉤霜雪明 關注
7.3 2019.04.02 18:12 字數(shù) 1665 閱讀 1550評論 1喜歡 83
原文鏈接:https://yq.aliyun.com/articles/531067
本文主要介紹在使用阿里云Redis的開發(fā)規(guī)范,從下面幾個方面進行說明突琳。
- 鍵值設計
- 命令使用
- 客戶端使用
- 相關工具
通過本文的介紹可以減少使用Redis過程帶來的問題鬼贱。
一席噩、鍵值設計
1移必、key名設計
可讀性和可管理性
以業(yè)務名(或數(shù)據(jù)庫名)為前綴(防止key沖突)钻洒,用冒號分隔,比如業(yè)務名:表名:id
ugc:video:1
簡潔性
保證語義的前提下廊谓,控制key的長度,當key較多時麻削,內存占用也不容忽視蒸痹,例如:
user:{uid}:friends:messages:{mid}簡化為u:{uid}:fr:m:{mid}。
不要包含特殊字符
反例:包含空格碟婆、換行电抚、單雙引號以及其他轉義字符
2惕稻、value設計
(1).【強制】:拒絕bigkey(防止網(wǎng)卡流量竖共、慢查詢)
防止網(wǎng)卡流量、慢查詢俺祠,string類型控制在10KB以內公给,hash、list蜘渣、set淌铐、zset元素個數(shù)不要超過5000。
反例:一個包含200萬個元素的list蔫缸。
非字符串的bigkey腿准,不要使用del刪除,使用hscan拾碌、sscan吐葱、zscan方式漸進式刪除,同時要注意防止bigkey過期時間自動刪除問題(例如一個200萬的zset設置1小時過期校翔,會觸發(fā)del操作弟跑,造成阻塞,而且該操作不會不出現(xiàn)在慢查詢中(latency可查))防症,查找方法和刪除方法
(2).【推薦】:選擇適合的數(shù)據(jù)類型
例如:實體類型(要合理控制和使用數(shù)據(jù)結構內存編碼優(yōu)化配置,例如ziplist孟辑,但也要注意節(jié)省內存和性能之間的平衡)。
反例:
set user:1:name tomset user:1:age 19set user:1:favor football
正例:
hmset user:1 name tom age 19 favor football
(3).【推薦】:控制key的生命周期蔫敲,redis不是垃圾桶
redis不是垃圾桶饲嗽,建議使用expire設置過期時間(條件允許可以打散過期時間,防止集中過期)奈嘿,不過期的數(shù)據(jù)重點關注idletime喝噪。
二、命令使用
1指么、O(N)命令關注N的數(shù)量
例如hgetall酝惧、lrange榴鼎、smembers、zrange晚唇、sinter等并非不能使用巫财,但是需要明確N的值。有遍歷的需求可以使用hscan哩陕、sscan平项、zscan代替。
2悍及、禁用命令
禁止線上使用keys闽瓢、flushall、flushdb等心赶,通過redis的rename機制禁掉命令扣讼,或者使用scan的方式漸進式處理。一個致命的 Redis 命令缨叫,導致公司損失 400 萬M址!關注Java技術棧微信公眾號耻姥,在后臺回復關鍵字:redis销钝,可以獲取更多棧長整理的 Redis 系列技術干貨。
3琐簇、合理使用select
redis的多數(shù)據(jù)庫較弱蒸健,使用數(shù)字進行區(qū)分,很多客戶端支持較差婉商,同時多業(yè)務用多數(shù)據(jù)庫實際還是單線程處理似忧,會有干擾。
4据某、使用批量操作提高效率
- 原生命令:例如mget橡娄、mset。
- 非原生命令:可以使用pipeline提高效率癣籽。
但要注意控制一次批量操作的元素個數(shù)(例如500以內挽唉,實際也和元素字節(jié)數(shù)有關)。
注意兩者不同:
- 原生是原子操作筷狼,pipeline是非原子操作瓶籽。
- pipeline可以打包不同的命令,原生做不到
- pipeline需要客戶端和服務端同時支持埂材。
5塑顺、不建議過多使用Redis事務功能
Redis的事務功能較弱(不支持回滾),而且集群版本(自研和官方)要求一次事務操作的key必須在一個slot上(可以使用hashtag功能解決)。分布式事務不理解严拒?一次給你講清楚扬绪!
6、Redis集群版本在使用Lua上有特殊要求
1裤唠、所有key都應該由 KEYS 數(shù)組來傳遞挤牛,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" 2、所有key航瞭,必須在1個slot上诫硕,否則直接返回error, "-ERR eval/evalsha command keys must in same slotrn"
7、monitor命令
必要情況下使用monitor命令時刊侯,要注意不要長時間使用章办。
三、客戶端使用
1滔吠、避免多個應用使用一個Redis實例
不相干的業(yè)務拆分纲菌,公共數(shù)據(jù)做服務化挠日。
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();
}
3只冻、熔斷功能
高并發(fā)下建議客戶端添加熔斷功能(例如netflix hystrix)
4、合理的加密
設置合理的密碼计技,如有必要可以使用SSL加密訪問(阿里云Redis支持)
5喜德、淘汰策略
根據(jù)自身業(yè)務類型,選好maxmemory-policy(最大內存淘汰策略)垮媒,設置好過期時間舍悯。
默認策略是volatile-lru,即超過最大內存后睡雇,在過期鍵中使用lru算法進行key的剔除萌衬,保證不過期數(shù)據(jù)不被刪除,但是可能會出現(xiàn)OOM問題它抱。
其他策略如下:
- allkeys-lru:根據(jù)LRU算法刪除鍵混移,不管數(shù)據(jù)有沒有設置超時屬性饵隙,直到騰出足夠空間為止勺届。
- allkeys-random:隨機刪除所有鍵饼酿,直到騰出足夠空間為止故俐。
- volatile-random:隨機刪除過期鍵喻犁,直到騰出足夠空間為止还栓。
- volatile-ttl:根據(jù)鍵值對象的ttl屬性慨蛙,刪除最近將要過期數(shù)據(jù)。如果沒有,回退到noeviction策略玖绿。
- noeviction:不會剔除任何數(shù)據(jù)蚀瘸,拒絕所有寫入操作并返回客戶端錯誤信息"(error) OOM command not allowed when used memory",此時Redis只響應讀操作苏章。
四寂嘉、相關工具
1、數(shù)據(jù)同步
redis間數(shù)據(jù)同步可以使用:redis-port
2枫绅、big key搜索
3泉孩、熱點key尋找
內部實現(xiàn)使用monitor,所以建議短時間使用facebook的redis-faina
阿里云Redis已經在內核層面解決熱點key問題
五并淋、刪除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);
}