Nchan 实时消息ha 配置

备注:
 
   Nchan 的数据持久化,以及ha 都是通过redis实现的,如果要做到无单点可以使用redis cluster 
   同对于Nchan server 进行多副本
 
1. 安装
下载nginx or openresty 源码同时下载Nchan 源码进行编译打包即可
 2. 简单sub/pub 配置
location 配置
      location = /sub {
          nchan_subscriber;
          nchan_channel_id $arg_id;
          nchan_use_redis on; // 关键
        } 
   
        location = /pub {
          nchan_publisher;
          nchan_channel_id $arg_id;
          nchan_use_redis on; // 关键
        }
redis server 配置
     nchan_redis_url "redis://127.0.0.1:6379";
3. ha 配置(伪ha,实际就是nginx 反向代理两台编译了Nchan 的nginx)
lb 配置

  server:
   server {
     listen 8089;
     location / {
          proxy_pass http://ws;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
     }
    }

    upstream:
    upstream ws {
       server xxxxxx:80 weight=2 max_fails=2 fail_timeout=30s;
       server xxxxxxxx:8090 weight=1 max_fails=2 fail_timeout=30s;
    }
Nchan 配置:
    参考上面的,必须在一台机器
   
redis cluster 版本的配置

http {
  upstream redis_cluster {
    nchan_redis_server redis://127.0.0.1:7000;
    nchan_redis_server redis://127.0.0.1:7001;
    nchan_redis_server redis://127.0.0.1:7002;
    # you don't need to specify all the nodes, they will be autodiscovered
    # however, it's recommended that you do specify at least a few master nodes.
  }
  server {
    listen 80;

    location ~ /sub/(\w+)$ {
      nchan_subscriber;
      nchan_channel_id $1;
      nchan_redis_pass redis_cluster;
    }
    location ~ /pub/(\w+)$ {
      nchan_publisher;
      nchan_channel_id $1;
      nchan_redis_pass redis_cluster;
    }
  }
} 
4. 测试
// http post data 

curl \
  -H "Content-type: application/json" \
  -d '{"name": "dalong","age":333}' \
  'http://xxxxx:8089/pub?id=demo'

// browser recived data
var ws =new WebScoket("ws://xxxxx:8089/sub?id=demo")
ws.onMessage=funciton(data){
   console.log(data)

}
  打开多个浏览器会发现数据是同步的,没有添加redis 的会出现数据无法接受到了
 
5. redis 数据存储查看
127.0.0.1:6379> KEYS *
 1) "{channel:/demo}"
 2) "{channel:/demo}:msg:1511175437:2"
 3) "{channel:/demo}:msg:1511175436:2"
 4) "{channel:/demo}:msg:1511175435:0"
 5) "{channel:/demo}:msg:1511175437:0"
 6) "{channel:/demo}:messages"
 7) "{channel:/demo}:msg:1511175436:0"
 8) "{channel:/demo}:msg:1511175437:3"
 9) "{channel:/demo}:msg:1511175424:1"
10) "{channel:/demo}:msg:1511175437:1"
11) "{channel:/demo}:msg:1511175436:3"
12) "{channel:/demo}:msg:1511175436:1"
6. 参考文档
https://nchan.io/#channel-multiplexing
https://nchan.io/documents/nginxconf2016-slides.pdf(很不错的分享)

posted on 2017-11-20 19:19  荣锋亮  阅读(937)  评论(0编辑  收藏  举报

导航