【问题标题】:Redis long-polling Pub/Sub frequent message blockingRedis 长轮询 Pub/Sub 频繁消息阻塞
【发布时间】:2013-07-28 15:41:03
【问题描述】:

我正在尝试围绕 Redis Pub/Sub API 进行思考并设置一个长轮询服务器。

此 lua 脚本订阅一个“测试”频道并返回收到的新消息:

nginx.conf:

location /poll {
  lua_need_request_body on;
  default_type 'text/plain';
  content_by_lua_file '/usr/local/nginx/html/poll.lua';
}

poll.lua:

local redis = require "redis";
local red = redis:new();
local cjson = require "cjson";

red:set_timeout(30000) -- 30 sec

local resCon, err = red:connect("127.0.0.1", 6379)
if not resCon then
  ngx.print("error")
  return
end

local resSub, err = red:subscribe('r:' .. ngx.var["arg_r"]:gsub('%W',''))

if not resSub then
  ngx.print("error")
  return
end

if resSub == ngx.null then
  ngx.print("error")
  return
end

local resMsg, err = red:read_reply()

if not resMsg then
  ngx.say("0")
  return
end

ngx.say(cjson.encode(resMsg))

client.js:

var tmpR = 'test';

function poll() {
  $.get('/poll', {'r':tmpR}, function(data){
    if (data !== "error") {
      console.log(data);
      window.setTimeout(function(){
        poll();
      },1000);
    } else {
      console.log('poll fail');
    }
  })
}

现在,如果我从 redis-cli 发送 publish r:test hello,我会在客户端收到消息,服务器会使用 1 响应 redis-cli。但是,如果我快速发送两条消息,第二条消息不会广播,服务器会以0 响应。

我的频道是否只能每秒接收一条消息,或者,这是否限制了用户可以向频道广播的消息频率?

假设许多用户可能同时连接,这是在 nginx 上接近这个轮询服务器的正确方法吗?在计时器上使用 GET 请求会更有效吗?

【问题讨论】:

    标签: nginx lua redis


    【解决方案1】:

    给定两条连续消息,只有一条消息会让订阅者收听结果。发送第二条消息时没有订阅者在监听。唯一的订阅者正在处理先前的结果并将其返回给用户。

    Redis不维护消息队列或类似的东西,以确保之前正在侦听的客户端将在重新连接时收到丢失的消息。

    【讨论】:

    • 你能详细说明一下吗?我刚刚用 2 个订阅者(同一台计算机上的 Safari / Chrome在两个地方都收到消息,或者它说1,它只发送给一个客户。我不太明白它为什么这样做。理想情况下,我会订阅 x 个客户,然后他们都会收到我从控制台发送的消息。
    • (是不是因为两个客户端都在同一个IP上并算作1个订阅者,那么当第一个收到消息时,它没有第二次传递到同一个IP?虽然,为什么有时有效?对于经常发送给单个客户端的消息,在第一条消息进入后重新连接和第二条消息之间重新连接之间是否有消息丢失?重新连接不应该花那么长时间。嗯。我不太明白发生了什么或它应该如何工作。)
    • "对于频繁发送给单个客户端的消息,在第一条消息进入后重新连接和第二条消息之间重新连接之间是否有消息丢失?"是的,我认为是这样。
    • 啊,当我发送一条消息并且只在一个地方收到它时,它似乎也源于频率。我想我只是错过了连接之间发送的消息。好的,现在这是有道理的。谢谢!
    猜你喜欢
    • 2014-10-11
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2012-04-25
    • 2015-11-09
    • 1970-01-01
    相关资源
    最近更新 更多