Centrifugo(七)Server HTTP API

    HTTP API 是最常用的向 Centrifugo 发送指令的一种方式。本文专门讲解 HTTP API。

  • Centrifugo API 的 url 为 /api/。如果你的 Centrifugo 服务域名是 https://centrifugo.rjguanwen.cn,那么 API 地址则是 https://centrifugo.rjguanwen.cn/api/

  • 当使用 HTTP API 时,你需要做的是向正确的地址发送正确构造的 POST 请求。

  • API 请求是一个 POST application/json 请求,指令包含在请求体,并带有一个附加的header X-API-Sign。请求体是 JSON 结构,其中包含了你需要执行的指令,指令可以是单条也可以是多条。

  • X-API-Sign 标头是基于 Centrifugo 密钥和要发送的 JSON 正文的 SHA-256 HMAC 字符串。该字符串主要用于 Centrifugo 对请求进行验证,以防假冒。在大多数情况下,你可以使用防火墙规则保护 Centrifugo API 端点,并且在 Centrifugo 启动时使用 --api_insecure 选项禁用验证检查。在此模式下,你使用 HTTP API 只需要发送 POST 请求,而不需要额外的 X-API-Sign 标头。

  • 请求体是 JSON 对象,包括两个属性:methodparams

    # 一条指令
    command = json.dumps({
        "method": "publish",
        "params": {"channel": "news", "data":{}}
    })

    # 多条指令
    command = json.dumps([
        {
            "method": "publish",
            "params": {"channel": "news", "data": {"content": "1"}}
        },
        {
            "method": "publish",
            "params": {"channel": "news", "data": {"content": "2"}}
        },
    ])
  • Centrifugo 已经提供了一些编程语言的官方 API client(API libraries)以方便调用 HTTP API。但是,你也可以不使用官方提供的 API client,而是自己编写程序发送请求,这样做也并不麻烦,而且可以减少你的应用程序的依赖。以 Python(使用 requests 库发送请求)为例:
import json
import requests

from cent.core import generate_api_sign

commands = [
    {
        "method": "publish",
        "params": {"channel": "docs", "data": {"content": "1"}}
    }
]

encoded_data = json.dumps(commands)
# 使用官方库中的方法来生成标识
sign = generate_api_sign('very-long-secret-key', encoded_data)
headers = {'Content-type': 'application/json', 'X-API-Sign': sign}
r = requests.post("https://centrifugo.rjguanwen.cn/api/, data=encoded_data, headers=headers)
print r.json()

    在上面的代码中,我们使用了官方提供的 Python 语言的 Cent 库中的方法来生成标识(sign)。你也可以自己构建标识。在上例中,commands 是一个数组,可以包含多条指令。

    我们可用的指令包括:publishbroadcastunsubscribepresencehistorydisconnectchannelsstatsnode

publish

    publish 指令用来向频道发送消息。publish 方法的 params 是一个 JSON 对象,至少包含两个 KEY :channeldata。从version 0.2.0之后,可以选择将客户端ID client 包含在 publish 指令中。

{
    "method": "publish",
    "params": {
        "channel": "CHANNEL NAME",
        "data": {
            "input": "hello"
        },
        "client": "long-unique-client-id"
    }
}

    响应示例:

{
    "body": null,
    "error": null,
    "method": "publish"
}

broadcast

    与 publish 基本类似,不过可以同时发布一条消息到多个渠道。

{
    "method": "broadcast",
    "params": {
        "channels": ["CHANNEL_1", "CHANNEL_2"],
        "data": {
            "input": "Hello"
        }
    }
}

    broadcast 指令同样可以包含 client 参数。
    本指令会将消息发送到所有指定队列直到第一个错误发生。当错误发生时,错误信息会以响应的方式返回,并且停止消息的继续发布。当使用 Redis API 时,错误信息无法返回,而是会记录日志。

unsubscribe

    unsubscribe 用来从渠道取消用户的订阅。params 包括两个 KEY:channeluser

    "method": "unsubscribe",
    "params": {
        "channel": "CHANNEL NAME",
        "user": "USER ID"
    }

    响应示例:

{
    "body": null,
    "error": null,
    "method": "unsubscribe"
}

disconnect

    disconnect 指令用来通过 ID 断开用户连接。params 包含一个 KEY:user

{
    "method": "disconnect",
    "params": {
        "user": "USER ID"
    }
}

    响应示例:

{
    "body": null,
    "error": null,
    "method": "disconnect"
}

presence

    presence 指令用来获取渠道的状态信息(当前订阅本渠道的所有客户端)。params 包含一个 KEY:channel

{
    "method": "presence",
    "params": {
        "channel": "CHANNEL NAME"
    }
}

    响应示例:

{
    "body": {
        "channel": "$public:chat",
        "data": {
            "a1c2f99d-fdaf-4e00-5f73-fc8a6bb7d239": {
                "user": "2694",
                "client": "a1c2f99d-fdaf-4e00-5f73-fc8a6bb7d239",
                "default_info": {
                    "first_name": "Alexandr",
                    "last_name": "Emelin"
                },
                "channel_info": {
                    "channel_extra_info_example": "you can add additional JSON data when authorizing"
                }
            },
            "e5ee0ab0-fde1-4543-6f36-13f2201adeac": {
                "user": "2694",
                "client": "e5ee0ab0-fde1-4543-6f36-13f2201adeac",
                "default_info": {
                    "first_name": "Alexandr",
                    "last_name": "Emelin"
                },
                "channel_info": {
                    "channel_extra_info_example": "you can add additional JSON data when authorizing"
                }
            }
        }
    },
    "error": null,
    "method": "presence"
}

history

    history 指令用来获取渠道的历史信息(发送到本渠道的最近的消息列表)。params 包含一个 KEY:channel

{
    "method": "history",
    "params": {
        "channel": "CHANNEL NAME"
    }
}

    响应示例:

{
    "body": {
        "channel": "$public:chat",
        "data": [
            {
                "uid": "8c5dca2e-1846-42e4-449e-682f615c4977",
                "timestamp": "1445536974",
                "info": {
                    "user": "2694",
                    "client": "a1c2f99d-fdaf-4e00-5f73-fc8a6bb7d239",
                    "default_info": {
                        "first_name": "Alexandr",
                        "last_name": "Emelin"
                    },
                    "channel_info": {
                        "channel_extra_info_example": "you can add additional JSON data when authorizing"
                    }
                },
                "channel": "$public:chat",
                "data": {
                    "input": "world"
                },
                "client": "a1c2f99d-fdaf-4e00-5f73-fc8a6bb7d239"
            },
            {
                "uid": "63ecba35-e9df-4dc6-4b72-a22f9c9f486f",
                "timestamp": "1445536969",
                "info": {
                    "user": "2694",
                    "client": "a1c2f99d-fdaf-4e00-5f73-fc8a6bb7d239",
                    "default_info": {
                        "first_name": "Alexandr",
                        "last_name": "Emelin"
                    },
                    "channel_info": {
                        "channel_extra_info_example": "you can add additional JSON data when authorizing"
                    }
                },
                "channel": "$public:chat",
                "data": {
                    "input": "hello"
                },
                "client": "a1c2f99d-fdaf-4e00-5f73-fc8a6bb7d239"
            }
        ]
    },
    "error": null,
    "method": "history"
}

channels

    channels 指令用来获取活动渠道列表(拥有至少一个订阅者)。

{
    "method": "channels",
    "params": {}
}

    响应示例:

{
    "body": {
        "data": [
            "$public:chat",
            "news",
            "notifications"
        ]
    },
    "error": null,
    "method": "channels"
}

stats

    stats 指令用来获取正在运行的 Centrifugo 节点的统计信息。

    "method": "stats",
    "params": {}

    响应示例:

{
    "body": {
        "data": {
            "nodes": [
                {
                    "uid": "6045438c-1b65-4b86-79ee-0c35367f29a9",
                    "name": "MacAir.local_8000",
                    "num_goroutine": 21,
                    "num_clients": 0,
                    "num_unique_clients": 0,
                    "num_channels": 0,
                    "started_at": 1445536564,
                    "gomaxprocs": 1,
                    "num_cpu": 4,
                    "num_msg_published": 0,
                    "num_msg_queued": 0,
                    "num_msg_sent": 0,
                    "num_api_requests": 0,
                    "num_client_requests": 0,
                    "bytes_client_in": 0,
                    "bytes_client_out": 0,
                    "memory_sys": 7444728,
                    "cpu_usage": 0
                }
            ],
            "metrics_interval": 60
        }
    },
    "error": null,
    "method": "stats"
}

node

    node 指令用来获取单个 Centrifugo 节点的信息。

{
    "method": "node",
    "params": {}
}

    响应示例:

{
    "body": {
        "data":{
            "uid":"c3ceab87-8060-4c25-9cb4-94eb9db7899a",
            "name":"MacAir.local_8000",
            "num_goroutine":14,
            "num_clients":0,
            "num_unique_clients":0,
            "num_channels":0,
            "started_at":1455450238,
            "gomaxprocs":4,
            "num_cpu":4,
            "num_msg_published":0,
            "num_msg_queued":0,
            "num_msg_sent":0,
            "num_api_requests":3,
            "num_client_requests":0,
            "bytes_client_in":0,
            "bytes_client_out":0,
            "memory_sys":0,
            "cpu_usage":0
        }
    },
    "error":null,
    "method":"node"
}