Skip to content

使用nchan构建全站推送

2022-04-08 nchan在实现 presence 相关方面是有欠缺的 无法实现拉取当前所有联系人 不方便跟踪房间进出详情 在经过调研后,决定弃用,使用 centrifugo-v3.1.1 来实现相关推送能力

nchan 官站

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 hundreds, 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 servers with Redis.

Messages are published to channels with HTTP POST requests or Websocket, and subscribed also through Websocket, long-polling, EventSource (SSE), old-fashioned interval polling, and more.

In a web browser, you can use Websocket or EventSource natively, or the NchanSubscriber.js wrapper library. It supports Long-Polling, EventSource, and resumable Websockets, and has a few other added convenience options. It's also available on NPM.

Features

简介

  • 以nginx module模式工作,高性能、可扩容、pub/sub推送服务。
  • subscribe客户端协议:websocket, sse, long-polling, http raw stream 等

  • 扩容模型是基于redis(单机性能会下降,但使用redis后总体支持连接数可线性扩容)

工作模型

架构图

客户端发送消息可以有2种方式:

  1. 直接使用客户端通过websocket发送上行消息
  2. 通过http post到接口,然后通过接口再次转发回到nchan进行广播

通过websocket发上行消息

sequenceDiagram

participant client as 客户端设备
participant im as nchanim
participant lemon as lemon

client ->> im: 建立连接
im ->> lemon: auth request
lemon -->> im: 200
im ->> lemon: nchan_subscribe_request/nchan_unsubscribe_request
client ->> im: websock send msg
im ->> lemon: nchan_publisher_upstream_request: msg forward auth

通过api发上行消息

sequenceDiagram

participant client as 客户端设备
participant im as nchanim
participant lemon as lemon

client ->> im: 建立连接
im ->> lemon: auth request
lemon -->> im: 200
im ->> lemon: nchan_subscribe_request/nchan_unsubscribe_request
client ->> api: post msg
api -->> api: spam check
api -->> im: pub msg
im -->> client: pub msg

特定逻辑详细分析

  • 如何做用户在线
  • 如何跟踪用户离线