一、发布publish/订阅subscribe
发布/订阅的实现过于简单,因为它只是分发消息,无法记录历史消息,例如网络断开、Redis宕机等消息就会丢弃,而在Redis5.0 新增了一个Redis Stream的数据结构,主要用于消息队列(MQ,message queue),它提供了消息的持久化和主备复制功能。
1. publish:向给定频道发送消息
2. subscribe:订阅给定的一个或多个频道
3. unsubscribe:退订给定的一个或多个频道,如果执行时没有给定任何频道,则退订所有频道
4. psubscribe:订阅给定的与pattern相匹配的频道
5. punsubscribe:退订给定的与pattern相匹配的频道,如果执行时没有给定任何频道,则退订所有频道
- # 1. subscribe:订阅给定的一个或多个频道
- 127.0.0.1:6379> subscribe mychannel
- subscribe
- mychannel
- 1
-
- # 2. publish:向给定频道发送消息
- # 再另外启动一个shell连接redis并执行下列命令
- 127.0.0.1:6379> publish mychannel "hello,world"
- 1
-
- # 返回前一个shell窗口,则显示
- 127.0.0.1:6379> subscribe mychannel
- subscribe
- mychannel
- 1
- message
- mychannel
- hello,world
-
- # 3. unsubscribe:退订给定的一个或多个频道,如果执行时没有给定任何频道,则退订所有频道
- 127.0.0.1:6379> unsubscribe mychannel
-
- # 4. psubscribe:订阅给定的与pattern相匹配的频道
- 略
-
- # 5. punsubscribe:退订给定的与pattern相匹配的频道,如果执行时没有给定任何频道,则退订所有频道
- 略
二、Hyperloglog
1. pfadd : 添加元素到hyperloglog中
2. pfcount:获取hyperloglog中的基数的估算值
3. pfmerge:将多个hyperloglog合并为一个hyperloglog
pf代表是这个数据结构的发明人Philippe Flajolet
hyperloglog可以用于统计一个网站的pv(unique view),也可以使用set来进行统计,这两个数据结构都有自动去重的功能。hyperloglog所占空间较小只需12KB内存即可,实现原理这里不详细展开。
如果使用set,当一个请求来了后sadd将用户id或ip地址放进去,并由scard统计数量即可,但是当一个页面有几千万的uv,这个很大的set集合就比较浪费空间。所以就引出了hyperloglog,它提供不精确的去重统计方案,标准误差在0.81%,可以满足上述UV统计。
用法与set相似,pfadd类似于sadd,pfcount类似于scard。
- # 1. pfadd : 添加元素到hyperloglog中
- 127.0.0.1:6379> pfadd myUV xiaoming
- 1
- 127.0.0.1:6379> pfadd myUV lihua
- 1
- 127.0.0.1:6379> pfadd myUV zhanghong
- 1
-
- 127.0.0.1:6379> pfadd youUV xiaoming
- 1
- 127.0.0.1:6379> pfadd youUV lihua
- 1
- 127.0.0.1:6379> pfadd youUV liuwei
- 1
- # 2. pfcount:获取hyperloglog中的基数的估算值
- 127.0.0.1:6379> pfcount myUV
- 3
- 127.0.0.1:6379> pfcount youUV
- 3
-
- # 3. pfmerge:将多个hyperloglog合并为一个hyperloglog
- 127.0.0.1:6379> pfmerge threeUV myUV youUV
- OK
- 127.0.0.1:6379> pfcount threeUV
- 4