Redis 數(shù)據(jù)結(jié)構(gòu)擴(kuò)展
0x01:Pipeline
在用 普通 jedis 方式連接 redis 的時(shí)候,由于每次發(fā)送命令都會(huì)與 redis 進(jìn)行連接,而實(shí)際處理命令的時(shí)間是非常短的,而連接卻十分耗時(shí),性能很低
n 個(gè)命令時(shí)間 = n 次連接時(shí)間 + n 次處理時(shí)間使用一個(gè)緩沖區(qū),命令全部寫(xiě)入緩沖區(qū)中,一次性發(fā)送給 redis,這樣就可以不用建立多次連接
n 個(gè)命令時(shí)間 = 1 次連接時(shí)間 + n 次處理時(shí)間注意:使用 Pipeline 的操作是非原子操作
Jedis jedis = new Jedis("127.0.0.1", 6379);
long start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
Pipeline pipeline = jedis.pipelined();
for (int j = i * 100; j < (i + 1) * 100; j++) {
pipeline.hset("bbbb" + j, "bbbb" + j, "bbbb" + j);
}
pipeline.syncAndReturnAll();
}
long end = System.currentTimeMillis();
System.out.println(end - start); // 118 ms
jedis.close();
0x02:GEO
是 zset 數(shù)據(jù)類(lèi)型的一個(gè)擴(kuò)展
127.0.0.1:6379> GEOADD locations 116.419217 39.921133 beijin
127.0.0.1:6379> GEOADD locations 117.23689,31.825596
127.0.0.1:6379> GEOPOS locations beijin
127.0.0.1:6379> GEODIST locations hefei beijin km // 計(jì)算距離
127.0.0.1:6379> GEORADIUSBYMEMBER locations beijin 150 km // 通過(guò)距離計(jì)算周邊城市
注意:沒(méi)有刪除命令 它的本質(zhì)是 zset (type locations)
所以可以使用 zrem key member 刪除元素
zrange key 0 -1 表示所有 返回指定集合中所有value
0x03:hyperLogLog
Redis 在 2.8.9 版本添加了 HyperLogLog 結(jié)構(gòu)。
Redis HyperLogLog 是用來(lái)做基數(shù)統(tǒng)計(jì)的算法,HyperLogLog 的優(yōu)點(diǎn)是,在輸入元素的數(shù)量或者體積非常非常大時(shí),計(jì)算基數(shù)所需的空間總是固定的、并且是很小的
在 Redis 里面,每個(gè) HyperLogLog 鍵只需要花費(fèi) 12 KB 內(nèi)存,就可以計(jì)算接近 2^64 個(gè)不同元素的基 數(shù)。這和計(jì)算基數(shù)時(shí),元素越多耗費(fèi)內(nèi)存就越多的集合形成鮮明對(duì)比。
127.0.0.1:6379> PFADD 2017_03_06:count 'yes' 'yes' 'yes' 'yes' 'no'
127.0.0.1:6379> PFCOUNT 2017_03_06:count # 統(tǒng)計(jì)有多少不同的值
127.0.0.1:6379> PFADD 2017_09_08:count uuid9 uuid10 uu11
127.0.0.1:6379> PFMERGE 2016_03_06:count 2017_09_08:count # 合并
注意:本質(zhì)還是字符串 ,有容錯(cuò)率,官方數(shù)據(jù)是0.81%
0x04:bitmaps
Bitmap 本質(zhì)是 string,是一串連續(xù)的 2 進(jìn)制數(shù)字( 0 或 1 ),每一位所在的位置為偏移(offset)。string(Bitmap)最大長(zhǎng)度是 512 MB,所以它們可以表示 2 ^ 32 = 4294967296 個(gè)不同的位。
127.0.0.1:6379> set test abc
OK
127.0.0.1:6379> get test
"abc" # 1100001 1100010 1100011
127.0.0.1:6379> setbit test 6 1
(integer) 0
127.0.0.1:6379> setbit test 7 0
(integer) 1
127.0.0.1:6379> get test
"bbc"
127.0.0.1:6379> setbit test 1000 0 # 擴(kuò)容至 1000 位,后面的用 0 填充
(integer) 0
127.0.0.1:6379> getbit test 1000 # 獲取第 1000 位
(integer) 0
127.0.0.1:6379> bitcount test # 統(tǒng)計(jì) 1
(integer) 10
應(yīng)用場(chǎng)景:
點(diǎn)贊功能:用戶(hù) ID 必須是數(shù)值類(lèi)型
點(diǎn)贊
setbit 朋友圈ID 用戶(hù)ID 1
取消點(diǎn)贊
setbit 朋友圈ID 用戶(hù)ID 0
統(tǒng)計(jì)點(diǎn)贊數(shù)
bitcount 朋友圈ID
查看是否點(diǎn)贊
getbit 朋友圈ID 用戶(hù)ID

喜歡,在看
