Nginx & Comet:低延迟信息推送

来源:互联网

原文链接:Nginx & Comet: Low Latency Server Push

服务器推送(Server Push)是高效的、延迟低的数据交换方式。如果数据发送端与接收端都在互联网中公开可见,可以使用PubSubHubbub或simpler Webhook等方法完成任务。但是如果数据接收方在防火墙内、在内网或它只是一个浏览器(只可以向外发送数据请求,无法处理传入的数据),则实现服务器推送就更难了。如果你有冒险精神,你可以建立一个反向HTTP服务器。如果你寻求可靠的解决方案,也许你要等待HTML5的WebSocket’s API特性了。但如果你需要即刻可以实现的解决方案,你可以妥协一下,使用异步推送模式来代替,你可以使用Comet,也被称为反向Ajax、HTTP服务器推送或HTTP流。

早在2006年Alex Russel提出了一个不坏的技术思路,那就是长连接(Comet)概念:从客户端发起并保持一个连接直到数据出现并传送(long polling),或者永远保持一个连接,通过它推送数据到客户端(streaming)。这两种方法的好处是数据传送非常及时。因此长连接技术广泛用于聊天应用(Facebook, Google, Meebo等)以及实现即时触发的机制。

Nginx变成一个长连接服务器

实现长连接服务比较大的问题是特殊的隐形需求以及事件驱动web服务器能否高效处理众多的长连接。Friendfeed的Tornado服务器是一个标准应用级服务器的好例子。另外,感谢Leo Ponomarev的努力,你现在可以用nginx_http_push_module插件使你的Nginx服务器变身成为一台完全功能的长连接服务器。

使用自定义的一套框架结构,Leo的插件只提供两个对外的接口:一个是订阅者,一个是发布者。客户端连接Nginx服务器,创建针对一个频道的long- polling长连接并等待数据。同时,发布者只是简单的将数据使用POST方法提交给Nginx,插件收到数据后将它一个个发给等待的客户端。这表明发布者不需要直接传递数据,它只是一个简单的事件产生器!

还有更强大的功能是,客户端和发布端可以建立任意的channel,插件提供消息队列功能,也就是说Nginx服务器会在客户端断线的情况下临时保存消息。队列消息可以按照时间、等待列表长度或内存限制大小来失效释放。

NginxRuby配置例子

首先,你需要从源代码编译一个Nginx。解压源代码包,从GitHub获取插件的源码并放入Nginx的源码目录,然后使用下面的参数编译(./configure –add-module=/path/to/plugin && make && make install)。下一步,参考readme文件和协议文件,了解所有的参数选项。一个多客户端接收信息的配置例子如下:

> nginx-push.conf

Java代码

  1. # internal publish endpoint (keep it private / protected)  
  2. # 内部发布点(保证私有或不对外公开)  
  3. location /publish {  
  4.   set $push_channel_id $arg_id;      #/?id=239aff3 or somesuch  
  5.   push_publisher;  
  6.   push_store_messages on;            # enable message queueing  # 打开消息队列  
  7.   push_message_timeout 2h;           # expire buffered messages after 2 hours # 2小时后消息失效  
  8.   push_max_message_buffer_length 10; # store 10 messages # 保存10条消息  
  9.   push_min_message_recipients 0;     # minimum recipients before purge # 清除前面接收人数目  
  10. }  
  11. # public long-polling endpoint  
  12. # 公开的长连接接收点  
  13. location /activity {  
  14.   push_subscriber;  
  15.   # how multiple listener requests to the same channel id are handled  
  16.   # 每个channel  id能有多少客户端同时连接  
  17.   # - last: only the most recent listener request is kept, 409 for others.  
  18.   # – last: 只有最频繁请求的客户端能保持,其它连接返回409
  19.   # - first: only the oldest listener request is kept, 409 for others.  
  20.   # – first: 只有最早连接的那个客户端可以保持,其它连接返回409
  21.   # - broadcast: any number of listener requests may be long-polling.  
  22.   # – broadcast: 所有的客户端连接都会是长连接  
  23.   push_subscriber_concurrency broadcast;  
  24.   set $push_channel_id $arg_id;  
  25.   default_type  text/plain;  
# internal publish endpoint (keep it private / protected)
# 内部发布点(保证私有或不对外公开)
location /publish {
  set $push_channel_id $arg_id;      #/?id=239aff3 or somesuch
  push_publisher;
 
  push_store_messages on;            # enable message queueing  # 打开消息队列
  push_message_timeout 2h;           # expire buffered messages after 2 hours # 2小时后消息失效
  push_max_message_buffer_length 10; # store 10 messages # 保存10条消息
  push_min_message_recipients 0;     # minimum recipients before purge # 清除前面接收人数目
}
 
# public long-polling endpoint
# 公开的长连接接收点
location /activity {
  push_subscriber;
 
  # how multiple listener requests to the same channel id are handled
  # 每个channel  id能有多少客户端同时连接
  # - last: only the most recent listener request is kept, 409 for others.
  # – last: 只有最频繁请求的客户端能保持,其它连接返回409
  # - first: only the oldest listener request is kept, 409 for others.
  # – first: 只有最早连接的那个客户端可以保持,其它连接返回409
  # - broadcast: any number of listener requests may be long-polling.
  # – broadcast: 所有的客户端连接都会是长连接
  push_subscriber_concurrency broadcast;
  set $push_channel_id $arg_id;
  default_type  text/plain;
}

编译配置好Nginx,并且启动它,我们可以建立一个简单的广播场景,一个数据发送广播方,几个订阅信息接收方来测试我们的长连接服务器。

> comet-push-consume.rb

Java代码

  1. require 'rubygems'
  2. require 'em-http'
  3. def subscribe(opts)  
  4.   listener = EventMachine::HttpRequest.new('http://127.0.0.1/activity?id='+ opts[:channel]).get :head => opts[:head]  
  5.   listener.callback {  
  6.     # print recieved message, re-subscribe to channel with  
  7.     # 输出所获取的内容,并重新订阅这个频道  
  8.     # the last-modified header to avoid duplicate messages   
  9.     # 使用header last-modified去忽略之前已经获取的数据  
  10.     puts "Listener recieved: " + listener.response + "\\n"

  11.     modified = listener.response_header['LAST_MODIFIED']  
  12.     subscribe({:channel => opts[:channel], :head => {'If-Modified-Since' => modified}})  
  13.   }  
  14. end  
  15. EventMachine.run {  
  16.   channel = "pub"

  17.   # Publish new message every 5 seconds  
  18.   # 每5秒钟发布一个新的消息  
  19.   EM.add_periodic_timer(5) do

  20.     time = Time.now  
  21.     publisher = EventMachine::HttpRequest.new('http://127.0.0.1/publish?id='+channel).post :body => "Hello @ #{time}"

  22.     publisher.callback {  
  23.       puts "Published message @ #{time}"

  24.       puts "Response code: " + publisher.response_header.status.to_s  
  25.       puts "Headers: " + publisher.response_header.inspect  
  26.       puts "Body: \\n" + publisher.response  
  27.       puts "\\n"

  28.     }  
  29.   end  
  30.   # open two listeners (aka broadcast/pubsub distribution)  
  31.   # 打开两个客户端  
  32.   subscribe(:channel => channel)  
  33.   subscribe(:channel => channel)  
require 'rubygems'
require 'em-http'
 
def subscribe(opts)
  listener = EventMachine::HttpRequest.new('http://127.0.0.1/activity?id='+ opts[:channel]).get :head => opts[:head]
  listener.callback {
    # print recieved message, re-subscribe to channel with
    # 输出所获取的内容,并重新订阅这个频道
    # the last-modified header to avoid duplicate messages 
    # 使用header last-modified去忽略之前已经获取的数据
    puts "Listener recieved: " + listener.response + "\\n"
 
    modified = listener.response_header['LAST_MODIFIED']
    subscribe({:channel => opts[:channel], :head => {'If-Modified-Since' => modified}})
  }
end
 
EventMachine.run {
  channel = "pub"
 
  # Publish new message every 5 seconds
  # 每5秒钟发布一个新的消息
  EM.add_periodic_timer(5) do
    time = Time.now
    publisher = EventMachine::HttpRequest.new('http://127.0.0.1/publish?id='+channel).post :body => "Hello @ #{time}"
    publisher.callback {
      puts "Published message @ #{time}"
      puts "Response code: " + publisher.response_header.status.to_s
      puts "Headers: " + publisher.response_header.inspect
      puts "Body: \\n" + publisher.response
      puts "\\n"
    }
  end
 
  # open two listeners (aka broadcast/pubsub distribution)
  # 打开两个客户端
  subscribe(:channel => channel)
  subscribe(:channel => channel)
}

 

nginx-push.zip (Full Nginx Config + Ruby client)

Downloads: 270 File Size: 2.7 KB

在上面的代码中,每5秒钟数据发布端向Nginx发出新的事件,nginx将数据通过长连接转发给两个订阅的客户端。当消息发送到客户端,服务器会断开他们的连接,客户端会立即重连并等待下一次数据的到来。这样,就实现了Nginx将一个数据发布端到客户端的实时消息推送机制!

Long Polling, Streaming, and Comet in Production

Leo的模块还在开发期,还需要时间来稳定下来,但它是一个需要关注的项目。最近的更新计划都着重于bug修复,未来的计划里有描述要加入流的模式:代替现在每次数据获取后都要重连的情况(long polling),Nginx会保持连接,将数据一段段的实时传送给客户端。拥有这个功能后你能很方便的部署你自己的信息触发式API(例如:Twitter流)。

发表评论