Centrifugo 6.10 常用 CLI 命令详解

Centrifugo v6.10.1 全部 13 个 CLI 子命令详解:令牌四件套与配置四件套逐参数实测回显,含错误分支、注意事项与常见问题。

Centrifugo即时通信Centrifugo2026/10/21

Centrifugo 6.10 常用 CLI 命令详解

目标:逐一详解 Centrifugo v6.10.1 命令行工具的全部 13 个子命令与全局参数,覆盖配置生成/校验、连接与订阅 JWT 的签发校验、内置参数文档生成等日常运维场景,全部命令与回显实测照录。已在 Ubuntu 22.04.5 LTS(x86_64)+ Centrifugo v6.10.1 服务器实测通过。

一、环境信息

  • 操作系统:Ubuntu 22.04.5 LTS(x86_64)
  • Centrifugo 版本:v6.10.1(Go version: go1.27.3),二进制路径 /usr/bin/centrifugo
  • 配置文件:/etc/centrifugo/config.json(服务端口 8130,默认 8000 被占用改为 8130)
  • 运行方式:systemd 服务 centrifugo.service

二、工具概览

2.1 命令体系总览

Centrifugo 的 CLI 有一个特别之处:主服务不带子命令启动(centrifugo -c config.json),其余子命令都是围绕配置与令牌的辅助工具。查看顶层帮助:

centrifugo --help

实测回显:

Centrifugo – scalable real-time messaging server in language-agnostic way

Usage:
   [flags]
   [command]

Available Commands:
  checkconfig   Check configuration file
  checksubtoken Check subscription JWT
  checktoken    Check connection JWT
  completion    Generate the autocompletion script for the specified shell
  configdoc     Show Centrifugo configuration documentation generated from source code
  defaultconfig Generate full configuration file with defaults
  defaultenv    Generate full environment var list with defaults
  genconfig     Generate minimal configuration file to start with
  gensubtoken   Generate sample subscription JWT for user
  gentoken      Generate sample connection JWT for user
  help          Help about any command
  serve         Run static file server (for development only)
  version       Centrifugo version information

Flags:
      --admin.enabled                         enable admin web interface
      --admin.external                        expose admin web interface on external port
      --admin.insecure                        use insecure admin mode – no auth required for admin socket
      --broker.enabled                        enable broker
      --broker.type string                    broker to use: memory, redis or nats (default "memory")
      --client.insecure                       start in insecure client mode
  -c, --config string                         path to config file (default "config.json")
      --debug.enabled                         enable debug endpoints
      --engine.type string                    engine to use: memory or redis (default "memory")
      --grpc_api.enabled                      enable GRPC API server
      --grpc_api.port int                     port to bind GRPC API server to (default 10000)
      --health.enabled                        enable health check endpoint
  -h, --help            help for this command
  -a, --http_server.address string            interface address to listen on
      --http_server.internal_address string   custom interface address to listen on for internal endpoints
      --http_server.internal_port string      custom port for internal endpoints
  -p, --http_server.port string               port to bind HTTP server to (default "8000")
      --http_stream.enabled                   enable bidirectional HTTP-streaming endpoint (with emulation layer)
      --init.enabled                          enable connection init endpoint
      --log.file string                       optional log file - if not specified logs go to STDOUT
      --log.level string                      set the log level: trace, debug, info, warn, error, fatal or none (default "info")
      --map_broker.type string                map broker to use: memory, redis or postgres (default "memory")
      --pid_file string                       optional path to create PID file
      --presence_manager.enabled              enable presence manager
      --presence_manager.type string          presence manager to use: memory or redis (default "memory")
      --prometheus.enabled                    enable Prometheus metrics endpoint
      --sse.enabled                           enable bidirectional SSE (EventSource) endpoint (with emulation layer)
      --swagger.enabled                       enable Swagger UI endpoint describing server HTTP API
      --uni_grpc.enabled                      enable unidirectional GRPC endpoint
      --uni_grpc.port int                     port to bind unidirectional GRPC server to (default 11000)
      --uni_http_stream.enabled               enable unidirectional HTTP-streaming endpoint
      --uni_sse.enabled                       enable unidirectional SSE (EventSource) endpoint
      --uni_websocket.enabled                 enable unidirectional websocket endpoint

Use " [command] --help" for more information about a command.

13 个子命令按用途分四类:

分类子命令一句话用途
令牌工具gentoken、checktoken、gensubtoken、checksubtoken连接/订阅 JWT 的签发与校验
配置工具genconfig、defaultconfig、defaultenv、checkconfig初始/全量配置与环境变量生成、配置校验
文档工具configdoc从二进制生成参数文档
辅助命令version、serve、completion、help版本、静态文件服务器、Shell 补全

2.2 主服务启动形态

生产主服务由 systemd 调用,等价的手工启动命令是直接带 flags(无子命令):

centrifugo -c /etc/centrifugo/config.json

启动后日志确认监听(实测,本文环境含额外开启的端点):

{"level":"info","time":"2026-10-21T15:09:26Z","message":"serving websocket, http_stream, sse, emulation, api, admin, prometheus, health, swagger endpoints on 0.0.0.0:8130"}

命令行 flags 与配置文件可混用(优先级 flags > 环境变量 > 配置文件),例如临时换端口试跑 centrifugo -c /etc/centrifugo/config.json -p 8132,实测日志确认监听 8132。常用启动 flags:-c 配置路径(默认 config.json)、-p 端口(默认 "8000")、-a 绑定地址、--engine.type 引擎、--log.level 日志级别、--pid_file PID 文件。

2.3 前置条件

  1. 二进制已安装(安装方法见《Ubuntu 22.04 安装 Centrifugo 指南》)。
  2. 令牌类与配置生成类子命令依赖配置文件(要读 hmac_secret_key 等密钥),操作生产密钥时用 -c /etc/centrifugo/config.json 明确指定。
  3. 无需 root:除写系统目录外,全部子命令普通用户可执行。

三、版本命令:version 与无效 flag

version 子命令输出版本与编译信息:

centrifugo version

实测回显:

Centrifugo v6.10.1 (Go version: go1.27.3)

注意没有 --version 全局 flag,误用会报错:

centrifugo --version

实测回显(首行):

Error: unknown flag: --version

四、令牌工具:gentoken / checktoken / gensubtoken / checksubtoken

Centrifugo 用 JWT 做客户端鉴权:**连接令牌(connection JWT)**证明"你是谁",**订阅令牌(subscription JWT)**授权"能订阅哪个私有频道"。四个子命令即两对签发/校验工具,签名算法取配置 client.token.hmac_secret_key(默认 HMAC SHA-256)。

4.1 gentoken:签发连接 JWT

查看帮助:

centrifugo gentoken --help

实测回显:

Generate sample connection JWT for user

Usage:
   gentoken [flags]

Flags:
  -c, --config string   path to config file (default "config.json")
  -h, --help            help for gentoken
  -q, --quiet           only output the token without anything else
  -t, --ttl int         token TTL in seconds, use -1 for token without expiration (default 604800)
  -u, --user string     user ID, by default anonymous

参数默认值:TTL 604800 秒(7 天);不带 -u 生成匿名令牌;-t -1 生成永不过期令牌;-q 只输出令牌本体(便于脚本取用)。实测三种形态:

centrifugo gentoken -c /etc/centrifugo/config.json -u 42 -t 3600

实测回显:

HMAC SHA-256 JWT for user "42" with expiration TTL 1h0m0s:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsImV4cCI6MTc5MjU5OTEyOCwiaWF0IjoxNzkyNTk1NTI4fQ.2RmvtVqaHZE2FmHOVBIzgickqp2mqH9_EQCSZsmuISs
centrifugo gentoken -c /etc/centrifugo/config.json -t 3600

实测回显(匿名):

HMAC SHA-256 JWT for anonymous user with expiration TTL 1h0m0s:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3OTI1OTk3MTQsImlhdCI6MTc5MjU5NjExNH0.aFkdlcs2R8B3oGWXT4fs9A9ULnPj6KdIUQdWtk27HT0
centrifugo gentoken -c /etc/centrifugo/config.json -u 42 -t -1

实测回显(永不过期):

HMAC SHA-256 JWT for user "42" without expiration:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsImlhdCI6MTc5MjU5NjExNH0.ylZ9-NqN7zJ1Us3dxZNwxvQpmHe8ND2St3kd8Xob8YE

⚠️ 注意:此命令生成的 JWT 只含 sub/iat/exp 标准声明,是联调与测试用的样例令牌。生产应由自研后端按官方 SDK(centrifuge-js 等)签发,可附加自定义 claims(如姓名、头像);密钥格式需与配置一致。

4.2 checktoken:校验连接 JWT

centrifugo checktoken --help

实测回显:

Check connection JWT

Usage:
   checktoken [TOKEN] [flags]

Flags:
  -c, --config string   path to config file (default "config.json")
  -h, --help            help for checktoken

令牌以位置参数传入。校验合法令牌:

T=$(centrifugo gentoken -c /etc/centrifugo/config.json -u 42 -t 3600 -q)
centrifugo checktoken -c /etc/centrifugo/config.json "$T"

实测回显:

valid token for user 42
payload: {"sub":"42","exp":1792599714,"iat":1792596114}
{"level":"info","algorithms":"HS256, HS384, HS512","time":"2026-10-21T15:21:54Z","message":"enabled JWT verifiers"}

篡改签名后校验(错误分支实测):

centrifugo checktoken -c /etc/centrifugo/config.json "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiJ9.bad_signature_here"; echo "rc=$?"

实测回显:

{"level":"info","algorithms":"HS256, HS384, HS512","time":"2026-10-21T15:21:54Z","message":"enabled JWT verifiers"}
error: token with algorithm HS256 and claims {"sub":"42"} has error: invalid token: signature is not valid
rc=1

4.3 gensubtoken:签发订阅 JWT

比 gentoken 多一个 -s/--channel 参数指定频道:

centrifugo gensubtoken --help

实测回显:

Generate sample subscription JWT for user

Usage:
   gensubtoken [flags]

Flags:
  -s, --channel string   channel
  -c, --config string    path to config file (default "config.json")
  -h, --help             help for gensubtoken
  -q, --quiet            only output the token without anything else
  -t, --ttl int          token TTL in seconds, use -1 for token without expiration (default 604800)
  -u, --user string      user ID

实测签发(用户 42 订阅频道 chat:main,1 小时有效):

centrifugo gensubtoken -c /etc/centrifugo/config.json -u 42 -s "chat:main" -t 3600

实测回显:

HMAC SHA-256 JWT for user "42" and channel "chat:main" with expiration TTL 1h0m0s:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsImV4cCI6MTc5MjU5OTcxMywiaWF0IjoxNzkyNTk2MTEzLCJjaGFubmVsIjoiY2hhdDptYWluIn0.RyIHy2O64j8pGOkOfJGfjeYHSpFoPqr6xV1hCXRkkB8

4.4 checksubtoken:校验订阅 JWT

ST=$(centrifugo gensubtoken -c /etc/centrifugo/config.json -u 42 -s "chat:main" -t 3600 -q)
centrifugo checksubtoken -c /etc/centrifugo/config.json "$ST"

实测回显:

valid subscription token for user "42" and channel "chat:main"
payload: {"sub":"42","exp":1792599714,"iat":1792596114,"channel":"chat:main"}
{"level":"info","algorithms":"HS256, HS384, HS512","time":"2026-10-21T15:21:54Z","message":"enabled JWT verifiers"}

payload 中的 channel 声明把令牌锁死在单一频道,这是私有频道($ 前缀)订阅授权的凭据形态。

五、配置工具:checkconfig / genconfig / defaultconfig / defaultenv

5.1 checkconfig:配置校验

centrifugo checkconfig --help

实测回显:

Check Centrifugo configuration file

Usage:
   checkconfig [flags]

Flags:
  -c, --config string   path to config file to check (default "config.json")
  -h, --help            help for checkconfig
  -s, --strict          strict check - fail on unknown fields

三个实测分支——合法配置静默通过:

centrifugo checkconfig -c /etc/centrifugo/config.json && echo OK
OK

坏 JSON 报解析错误(退出码 1):

echo '{bad json' > /tmp/bad.json
centrifugo checkconfig -c /tmp/bad.json; echo "rc=$?"
error getting config: error reading config file /tmp/bad.json: While parsing config: invalid character 'b' looking for beginning of object key string
rc=1

严格模式拒绝未知字段(跨版本升级迁移配置的核对利器):

printf '{"client":{"token":{"hmac_secret_key":"x"}},"typo_key":1}' > /tmp/unk.json
centrifugo checkconfig -c /tmp/unk.json; echo "rc_loose=$?"
centrifugo checkconfig -s -c /tmp/unk.json; echo "rc_strict=$?"
rc_loose=0
unknown keys in config: typo_key
rc_strict=1

💡 说明:deb 包的 systemd 单元把 checkconfig 挂在 ExecStartPre,配置非法时服务拒绝启动——这也是安装后启动失败排障的第一入口(详见安装篇 FAQ)。

5.2 genconfig:生成最小配置

centrifugo genconfig --help

实测回显:

Generate minimal configuration file to start with

Usage:
   genconfig [flags]

Flags:
  -c, --config string   path to output config file (default "config.json")
  -h, --help            help for genconfig

实测生成(每次运行密钥都随机不同,且文件以 0600 权限写出):

centrifugo genconfig -c /tmp/gen.json && cat /tmp/gen.json

实测回显:

{
  "client": {
    "token": {
      "hmac_secret_key": "kRWifSdKgHtwrLteIjTD_moyHP5EjkE2-3d1lPLtnEz8mxyvXw0vZHQGeAmphS3p9Sy4yOkNqWe38amnyLQxbw"
    },
    "allowed_origins": []
  },
  "admin": {
    "enabled": false,
    "password": "Vs2QilwteWPVIi3NbFgbgA",
    "secret": "PKsdVKDKA41neEPdk4UGI-i9_r8v2w3URA-Gc_PoJi04lucaIQ1uS6FpcBu61s_JwPn_I75xqVP4fHR3Z54p3Q"
  },
  "http_api": {
    "key": "Op6reF0mcjql_e8qOM_lfJ9oaYvEyMO6qqH_nA6ql7zlerA3JT4z0vGvTFnKU0GegE1ljB2mNuPHnjEyAmBsnA"
  }
}

⚠️ 注意:0600 权限对命令行手工使用无碍,但交给 centrifugo 服务用户运行前必须调整为 root:centrifugo 640,否则服务读不到配置(安装篇 4.5 节排障实录)。

5.3 defaultconfig:生成全量默认配置

centrifugo defaultconfig --help

实测回显:

Generate full Centrifugo configuration file with defaults

Usage:
   defaultconfig [flags]

Flags:
  -b, --base string     path to the base config file to use
  -c, --config string   path to default config file to generate (default "config.json")
  -d, --dry-run         dry run mode (do not write file and just print generated config to stdout)
  -h, --help            help for defaultconfig

-d dry-run 只打印不落盘(输出节选):

centrifugo defaultconfig -d | head -20
{
  "http_server": {
    "address": "",
    "port": 8000,
    "internal_address": "",
    "internal_port": "",
    "tls": {
      "enabled": false,
      "cert_pem": "",
      "key_pem": "",
      "server_ca_pem": "",
      "client_ca_pem": "",
      "insecure_skip_verify": false,
      "server_name": ""
    },

全量输出 1095 行,可写盘后按需精简成生产配置;-b 允许以现有配置为基底合并默认值。

5.4 defaultenv:生成环境变量清单

centrifugo defaultenv --help

实测回显:

Generate full Centrifugo environment var list with defaults

Usage:
   defaultenv [flags]

Flags:
  -b, --base string          path to the base config file to use
      --base-non-zero-only   only output environment variables for values which were non zero in base config file
  -h, --help                 help for defaultenv

实测(全量 855 行,节选头部):

centrifugo defaultenv | head -6; centrifugo defaultenv | wc -l
CENTRIFUGO_ADMIN_ENABLED=false
CENTRIFUGO_ADMIN_EXTERNAL=false
CENTRIFUGO_ADMIN_HANDLER_PREFIX=""
CENTRIFUGO_ADMIN_INSECURE=false
CENTRIFUGO_ADMIN_PASSWORD=""
CENTRIFUGO_ADMIN_SECRET=""
855

--base-non-zero-only 配合 -b 可只列出与基线配置有差异的变量,容器/K8s 场景注入用。

5.5 configdoc:生成参数文档

centrifugo configdoc --help

实测回显:

Show Centrifugo configuration documentation generated from source code

Usage:
   configdoc [flags]

Flags:
  -l, --base-level int   base level to use
  -h, --help            help for configdoc
  -m, --markdown         output markdown to stdout
  -p, --port int         port to run server on (default 6060)
  -s, --section string   filter by top-level section name

三种用法实测。Markdown 输出全量 10085 行(与运行版本严格一致,是查参数语义的权威离线手册):

centrifugo configdoc -m | wc -l
10085

按顶层段过滤:

centrifugo configdoc -m -s admin | head -8
# `admin`

Type: `Admin` object

Configures the admin web UI and its API endpoints.

## `admin.enabled`

不带 -m 时启动本地文档站点(默认 6060 端口,浏览器访问)——在无桌面的服务器上它不会自动开浏览器而打印提示:

Failed to open browser automatically: exec: "xdg-open,x-www-browser,www-browser": executable file not found in $PATH, see http://localhost:6060

此时手工访问 http://127.0.0.1:6060 即可阅读。

六、辅助命令:serve / completion / help

6.1 serve:静态文件服务器(开发用,不是主服务!)

centrifugo serve --help

实测回显:

Run static file server (for development only)

Usage:
   serve [flags]

Flags:
  -a, --address string   interface to serve on (default: all interfaces)
  -d, --dir string       path to directory (default "./")
  -h, --help             help for serve
  -p, --port int         port to serve on (default 3000)

⚠️ 注意:serve 不是启动 Centrifugo 消息服务器——它是把任意目录当静态站点服务的开发辅助命令(默认端口 3000)。主服务是不带子命令的 centrifugo -c ...。从老文档/教程迁移过来的读者极易在此踩坑(早期版本确有 centrifugo serve 启动主服务的用法,v6 已变)。

6.2 completion:Shell 自动补全

centrifugo completion --help

实测回显:

Generate the autocompletion script for  for the specified shell.
See each sub-command's help for details on how to use the generated script.

Usage:
   completion [command]

Available Commands:
  bash        Generate the autocompletion script for bash
  fish        Generate the autocompletion script for fish
  powershell  Generate the autocompletion script for powershell
  zsh         Generate the autocompletion script for zsh

Flags:
  -h, --help   help for completion

Use " completion [command] --help" for more information about a command.

bash 用户启用:

centrifugo completion bash | head -3

实测回显(节选):

# bash completion V2 for centrifugo                         -*- shell-script -*-

6.3 help

centrifugo help [command] 与 [command] --help 等价,例如 centrifugo help gentoken 输出与 4.1 节帮助一致。

七、注意事项

  1. 令牌工具是测试样例生成器:gentoken/gensubtoken 产物只含标准声明,生产环境应由应用后端用官方 SDK 签发带业务 claims 的 JWT;四个工具都要求能读到含密钥的配置文件。
  2. serve 语义已变:v6 中 serve 仅静态文件服务器;主服务无子命令直接启动(2.2 节)。
  3. 没有 --version flag:查版本用 centrifugo version 子命令。
  4. 密钥安全:genconfig/defaultconfig 输出含随机生成的密钥与口令,落到共享路径前注意文件权限(0600 起);生产密钥建议用 openssl rand -base64 48 自行生成后注入。
  5. checkconfig 退出码可用于流水线:0 合法、1 非法;strict 模式对未知字段零容忍,适合 CI 与升级前校验。
  6. 全量配置/环境变量/参数文档都有内置生成器(defaultconfig/defaultenv/configdoc),离线服务器无需翻网页。

八、常见问题

Q1:centrifugo gentoken 报 config file not found 或读不到密钥? 工作目录下没有 config.json 且未用 -c 指定路径。始终显式指定:centrifugo gentoken -c /etc/centrifugo/config.json ...。若当前用户无权限读该文件(默认 root:centrifugo 640),用 sudo 或加入 centrifugo 组。

Q2:checktoken 报 signature is not valid? 令牌签名与配置的 client.token.hmac_secret_key 不匹配——多半是签发方用了另一份密钥,或密钥轮换后旧令牌仍在用。用 checktoken 的 payload 输出确认声明,再核对两侧密钥。

Q3:centrifugo serve 起了个不对劲的东西? 见 6.1 节:serve 是静态文件服务器。启动消息服务器直接 centrifugo -c /etc/centrifugo/config.json(systemd 部署时 systemctl start centrifugo)。

Q4:生成的 JWT 客户端连接报 3501 bad request? 令牌本身没问题,是客户端协议用法问题:v6 每条 WebSocket 命令必须带自增 id 字段({"id":1,"connect":{...}})。CLI 排障时先用 checktoken 验令牌,再查客户端命令帧。

Q5:token 过期怎么算? -t 秒数换算(默认 604800=7 天),过期时间写进 JWT 的 exp 声明(checktoken payload 可见)。-t -1 生成永不过期令牌,仅限服务间信任场景,浏览器侧慎用。

九、参考链接