u1.subscribe "channel1" do |on|
on.subscribe do |channel, subscriptions|
puts "Subscribed to ##{channel} (#{subscriptions} subscriptions)"
end
on.message do |channel, msg|
puts "#{channel}: #{msg}"
end
end
u1进入监听等待状态
#Subscribed to #channel1 (1 subscriptions)
3,u2发布一条消息
u2.publish 'channel1', 'hello'
4,u1收到新的消息,并打印出来
#Subscribed to #channel1 (1 subscriptions)
#channel1: hello
5,block块中,有三种回调类型,已经看到的前2种,subscribe和message,第三种是unsubscribe。
redis.subscribe(:one, :two) do |on|
#channel:当前的频道,subscriptions: 第几个频道
on.subscribe do |channel, subscriptions|
puts "Subscribed to ##{channel} (#{subscriptions} subscriptions)"
end
#channel:当前的频道,message: 消息内容
on.message do |channel, message|
puts "##{channel}: #{message}"
redis.unsubscribe if message == "exit"
end
#
on.unsubscribe do |channel, subscriptions|
puts "Unsubscribed from ##{channel} (#{subscriptions} subscriptions)"
end
end
ps:代码来自https://github.com/redis/redis-rb/blob/master/examples/pubsub.rb
可以在消息定义各种规则,来实现频道的管理。
6,下面介绍一下发布和订阅相关的一些方法。
psubscribe。订阅给定的模式。
redis.psubscribe('c*') do |on|
on.psubscribe do |channel, subscriptions|
puts "Subscribed to ##{channel} (#{subscriptions} subscriptions)"
end
on.pmessage do |pattern, channel, message|
puts "##{channel}: #{message}"
redis.unsubscribe if message == "exit"
end
on.punsubscribe do |channel, subscriptions|
puts "Unsubscribed from ##{channel} (#{subscriptions} subscriptions)"
end
end
和subscribe的区别是参数是匹配的模式,block中的三个方法也对应的变化了。