Spring Data Redis-keyspace notifications

观察者模式

这种创建一个消息中心, 所有消息发布者发布消息到中心, 中心把消息通知到各订阅者的设计模式在GUI程序的事件模型中使用比较多。

而放在WEB应用中,主要用来解决流程计时, 以及代替轻量级的实时队列的功能(如计数的逻辑的异步)。

Channel

频道, 每一个订阅者可根据频道选择自己喜欢的信息,一个订阅者可能对多个频道有兴趣。 但一个消息发布者不宜把消息发布到多个频道中, 至于说为什么不宜发布到多个频道中, 我这暂时很难拿出一个合理的数学证明。 不过有个很简单的逻辑, 如果一个订阅者订阅了多个频道, 一个消息又发到了多个频道, 那么一个订阅者就可会收到重复的消息,即使消息中心应该处理这个重复的消息, 但明显处理逻辑增加了,遍历订阅者的次数也增加了。 具体分析依赖于实现。

=== Keyspace Notifications

其官网这样描述

Keyspace notifications allows clients to subscribe to Pub/Sub channels in order to receive events affecting the Redis data set in some way.
Examples of the events that is possible to receive are the following:
All the commands affecting a given key.
All the keys receiving an LPUSH operation.
All the keys expiring in the database 0.
Events are delivered using the normal Pub/Sub layer of Redis, so clients implementing Pub/Sub are able to use this feature without modifications.

Redis 是一个键值对的系统, 其数据变化会产生事件, 具体内容可参考 http://redis.io/topics/notifications

这里我想用来做流程计时, 所以关心的是 EXPIRE 事件。 Keyspace notifications 消耗CPU,默认是关闭的,所以需要在配置文件中声明, 下面是可控粒度。

K Keyspace events, published with keyspace@<db> prefix.
E Keyevent events, published with keyevent@<db> prefix.
g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
$ String commands
l List commands
s Set commands
h Hash commands
z Sorted set commands
x Expired events (events generated every time a key expires)
e Evicted events (events generated when a key is evicted for maxmemory)
A Alias for g$lshzxe, so that the "AKE" string means all the events.

Spring Data Redis

其配置可参考 http://docs.spring.io/spring-data/redis/docs/1.7.1.RELEASE/reference/html/#redis:pubsub:subscribe 没什么可说的, 但需要注意的是, 需要使用org.springframework.data.redis.listener.PatternTopic 来使得订阅者订阅多个频道。

其它

这里实现的观察者模式比较简单, 但事实上,我们也暂时不用去考虑观察者的冲突,时效,处理时间与堆积,处理优先的问题。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,868评论 18 139
  • # redis 配置文件示例 # 当你需要为某个配置项指定内存大小的时候,必须要带上单位, # 通常的格式就是 1...
    iyimao阅读 819评论 0 2
  • Redis 配置文件示例 注意:想要读取配置文件,Redis的第一个参数必须是文件的路径 ./redis-serv...
    起个名忒难阅读 1,223评论 0 1
  • 5/15/2017 7:06:35 PM 纵观各大组件,配置文件占据极其重要的地位。可配置化也是当下开发的一流行趋...
    爱做梦的胖子阅读 4,456评论 0 8
  • 今天就说教育课,从小孩子出生来到了这个世界的时候,哇哇大哭,看见了蓝色的天空,幸福的家庭。一天一天地长大,学会跟人...
    红火太阳阅读 177评论 0 0