1. 安装

支持

1.1. 安装方式 (源码构建)

git clone https://github.com/centrifugal/centrifugo.git

cd centrifugo

1.2. 环境

go version go1.11.4 darwin/amd64

1.3. go mod

go mod init

// go mod init (name) ## name 自己定义 这里使用空

1.4. 下载依赖

go mod vendor

go mod download

过程中需要* F *墙*

1.5. go build

生成 二进制文件
# https://centrifugal.github.io/centrifugo/server/install/

1.6. 配置文件

# https://centrifugal.github.io/centrifugo/server/configuration/
{
  "admin":true, # 开启web
  "secret": "secret",  # api 生成token
  "api_key":"api_key", # api 使用授权的apikey
  "admin_password": "web密码",
  "admin_secret": "admin->secret",
  "client_channel_limit":2, #设置单个客户端可以拥有的最大不同通道订阅数。
  "channel_max_length":255, #设置通道名称的最大长度。 默认255
  "client_anonymous":true, #匿名(具有空用户ID),只能订阅anonymous启用了选项的通道。
  "namespaces": [  ## 命名空间
    {
      "name": "abbb",
      "anonymous": false,
      "publish": true,
      "join_leave": true,
      "presence": true,
      "presence_stats": true,
      "history_size": 0,
      "history_lifetime": 0,
      "history_recover": false
    },
    {
      "name": "public", # channel 使用 【public:test】 那么使用 此配置项
      "anonymous": true, # 支持 匿名 【空用户ID ->生产的token】
      "publish": false, # 客户端 是否支持 发送消息
      "join_leave": false, # 启用/禁用发送加入(离开)消息。默认情况下false
      "presence": true, # 支持 频道的状态信息
      "presence_stats": true, # 统计客户端信息
      #  历史配置一起使用
      "history_size": 10, #支持历史消息 条数
      "history_lifetime": 60, #支持历史消息限制时间 *秒
      "history_recover": true # 客户端 意外断开 历史数据恢复
    }
  ]
}

1.7. PHP Server Api

composer require sl4mmer/phpcent

https://github.com/centrifugal/phpcent
https://github.com/oleh-ozimok/php-centrifugo/tree/v1.0
https://github.com/oleh-ozimok/php-centrifugo

1.8. 服务封装

<?php

namespace App\Services;

use App\Common\Functions;
use Illuminate\Foundation\Bus\DispatchesJobs;
/**
 * 离心机推送websocket
 * Class BlackHoleService
 * @package App\Services
 */
class BlackHoleService
{
    //DispatchesJobs
    use DispatchesJobs;
    private $Centrifugo;

    public function __construct(){
        $this->Centrifugo = new \phpcent\Client(env('CENT_URL',"http://host:8000/api"),env('CENT_API_KEY','apikey'),env('CENT_SECRET','secret'));
    }

    /**
     * 推送数据
     * @param $channel
     * @param $data
     * @return array
     */
    public function pubData($channel,$data)
    {
        try{
            if(empty($channel)){
                throw new \Exception("channel is nil.");
            }
            if(empty($data) ){
                throw new \Exception("data is nil.");
            }elseif(!is_array($data)){
                throw new \Exception("data Must be an array .");
            }
            $res = $this->Centrifugo->publish("{$channel}", $data);
            Functions::SysLog('BlackHoleService','== pubData SUC ==',[$channel,$data,$res]);
            return [true,$res];
        }catch (\Exception $e){
            Functions::SysLog('BlackHoleService','== pubData Exception ==',[[$channel,$data],$e->getMessage(),$e->getLine(),$e->getCode()]);
           return [false,$e->getMessage()];
        }
    }

    /**
     * 发送广播 $channels 空格 间隔
     * @param $channels
     * @param $data
     * @return array
     */
    public function pubBroadcast($channels, $data)
    {
        try{
            if(empty($channel)){
                throw new \Exception("channels is nil.");
            }
            if(empty($data) ){
                throw new \Exception("data is nil.");
            }elseif(!is_array($data)){
                throw new \Exception("data Must be an array .");
            }
            $res =  $this->Centrifugo->broadcast($channels, $data);
            Functions::SysLog('BlackHoleService','== pubBroadcast SUC ==',[$channels,$data,$res]);
            return [true,$res];
        }catch (\Exception $e){
            Functions::SysLog('BlackHoleService','== pubBroadcast Exception ==',[$e->getMessage(),$e->getLine(),$e->getCode()]);
            return [false,$e->getMessage()];
        }
    }
    /**
     * 获取授权token 默认 userId 空支持 anonymous
     * @param string $userId
     * @param int $exp
     * @param array $info
     * @return array
     */
    public function getToken($userId='',$exp=0,$info=[])
    {
        try{
            $token = $this->Centrifugo->generateConnectionToken($userId,$exp,$info);
            return [true,$token];
        }catch (\Exception $e){
            Functions::SysLog('BlackHoleService','== GetToken Exception ==',[[$userId,$exp,$info],$e->getMessage(),$e->getLine(),$e->getCode()]);
            return [false,$e->getMessage()];
        }
    }

    /**
     * 获取通道
     * @return mixed
     */
    public function getChannels(){
        try{
            $response = $this->Centrifugo->channels();
            return [true,Functions::object_array($response->result->channels)];
        }catch (\Exception $e){
            Functions::SysLog('BlackHoleService','== getChannels Exception ==',[$e->getMessage(),$e->getLine(),$e->getCode()]);
            return [false,$e->getMessage()];
        }
    }

    /**
     * 获取通道下的历史数据
     * @param $channel
     * @return array
     */
    public function getHistory($channel){
        try{
            $response = $this->Centrifugo->history($channel);
            return [true,Functions::object_array($response->result->publications)];
        }catch (\Exception $e){
            Functions::SysLog('BlackHoleService','== getHistory Exception ==',[$e->getMessage(),$e->getLine(),$e->getCode()]);
            return [false,$e->getMessage()];
        }
    }

    /**
     * 获取通道下的客户端
     * @param $channel
     * @return array
     */
    public function getClientsByChannel($channel){
        try{
            $response = $this->Centrifugo->presence($channel);
           return [true,Functions::object_array($response->result->presence)];
        }catch (\Exception $e){
            Functions::SysLog('BlackHoleService','== getClientsByChannel Exception ==',[$e->getMessage(),$e->getLine(),$e->getCode()]);
            return [false,$e->getMessage()];
        }
    }

    /**
     * 获取通道的统计信息
     * @param $channel
     * @return array
     */
    public function getStatsByChannel($channel){
        try{
            $response = $this->Centrifugo->presence_stats($channel);
            return [true,Functions::object_array($response->result)];
        }catch (\Exception $e){
            Functions::SysLog('BlackHoleService','== getStatsByChannel Exception ==',[$e->getMessage(),$e->getLine(),$e->getCode()]);
            return [false,$e->getMessage()];
        }
    }

}

results matching ""

    No results matching ""