redis ruby客户端学习(四)

redis是一个快速、稳定的发布/订阅的信息系统。

这里有相关的介绍

可以用这个发布订阅系统,实现聊天功能。

1,假设有两个用户,分别是user1和user2,各创建一个redis连接。

u1 = Redis.new
u2 = Redis.new

2,u1订阅一个频道channel1

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中的三个方法也对应的变化了。

 小结:这个主要介绍了redis中的发布和订阅相关的使用例子。一个用户可以订阅多个频道,也可以向多个频道发布消息。

原文地址:https://www.cnblogs.com/fanxiaopeng/p/4199819.html