# nginx 的 nchan 模塊
#### 1. 介紹

> Nchan is a scalable, flexible pub/sub server for the modern web, built as a module for the Nginx web server. It can be configured as a standalone > server, or as a shim between your application and tens, thousands, or millions of live subscribers. It can buffer messages in memory, on-disk, or > via Redis. All connections are handled asynchronously and distributed among any number of worker processes. It can also scale to many nginx > server instances with Redis.
[nchan](https://github.com/slact/nchan)是nginx的一個模塊,它的作用跟[nginx-push-stream-module](http://www.rails365.net/articles/websocket-wai-pian-nginx-push-stream-module-mo)一樣,也是結合nginx搭建websocket服務器,不過相比于`nginx-push-stream-module`,它更為強大。
比如,它可以指定redis作為適配器,還有,它具有**消息緩存(buffer messages)**的功能。
#### 2. 使用
下面就來演示一下,它是如何具有消息緩存(buffer messages)的功能的。
##### 2.1 安裝
首先來安裝。
安裝可以跟之前一樣,參考這篇文章[nginx之編譯第三方模塊(六)](http://www.rails365.net/articles/nginx-zhi-bian-yi-di-san-fang-mo-kuai-liu)。
```
./configure --add-module=path/to/nchan ...
```
或者,如果你在mac系統環境下,可以使用brew來安裝。
```
$ brew tap homebrew/nginx
$ brew install nginx-full --with-nchan-module
```
##### 2.2 配置
現在我們來配置一下,只要在`server`上放兩個`location`即可。
```
http {
server {
listen 80;
location = /sub {
nchan_subscriber;
nchan_channel_id foobar;
}
location = /pub {
nchan_publisher;
nchan_channel_id foobar;
}
}
}
```
##### 2.3 測試
接著,我們開啟瀏覽器發起websocket請求。
上面的配置中,訂閱相關的`location`是`/sub`,而發布相關的是`/pub`。
還是跟之前的一樣:
```
ws = new WebSocket("ws://localhost/sub");
ws.onmessage = function(evt){console.log(evt.data);};
```
然后我們給客戶端推送消息。
```
$ curl --request POST --data "test message" http://127.0.0.1:80/pub
queued messages: 1
last requested: 57 sec. ago
active subscribers: 1
last message id: 1462759616:0%
```
上面的命令表示使用post請求`pub`向客戶端推送`"test message"`這條消息。
瀏覽器也輸出了相應的信息`"test message"`。

這樣就跑通了整個流程。
##### 2.4 消息緩存(buffer messages)
然而我們需要來測試一下**消息緩存(buffer messages)**的功能。
先把瀏覽器關掉,這個時候,就沒有任何訂閱的客戶端了。
再推送一條消息。
```
$ curl --request POST --data "test message" http://127.0.0.1:80/pub
queued messages: 2
last requested: 2464 sec. ago
active subscribers: 0
last message id: 1462762080:0%
```
現在`"queued messages"`等于2,表示,在隊列中有兩條消息沒有推送,之前`"queued messages"`的值是為1的。
現在我們重新打開瀏覽器,并開啟之前的websocket請求。效果如下:

客戶端立即收到隊列中的兩條消息了。
這種模式,演示了,假如客戶端不在線,或掉線了之后,消息也能被正常的推送,它一上線,就能立即收到消息了。
如果我們再運行一次上面的curl命令,`"queued messages"`就會變成`"3"`。
默認情況下,這樣的消息最多存儲10條,當然這是可以配置的。
通過`"nchan_message_buffer_length"`就可以設置存儲的消息的個數,除了這些,還有以下配置:
- nchan\_message\_timeout 消息的存活時間
- nchan\_store\_messages 是否存儲消息,也就是開關功能
其他的功能可以查看官方的readme文檔。
本篇完結。