zoukankan      html  css  js  c++  java
  • 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中的发布和订阅相关的使用例子。一个用户可以订阅多个频道,也可以向多个频道发布消息。

  • 相关阅读:
    window linux pycharm 相互协作
    再次校验环境
    转 安装 ubuntu后 软件处理 -感谢博主skykingf csdn
    NSError是向用户传递详细错误信息的不错的选择
    Node.js学习笔记-入门
    UIKit和CSS布局方式的差异
    继承缺陷以及替代方案
    HTML、HTML DOM、Javascript、CSS以及jQuery使用小结
    关于cookies
    一个诡异bug---symbol not found: objc_setProperty_atomic
  • 原文地址:https://www.cnblogs.com/fanxiaopeng/p/4199819.html
Copyright © 2011-2022 走看看