thinkphp使用consul

service层

<?php
namespace app\service;

use http\Client;
use think\facade\Config;

class Consul
{
    private $httpUrl;
    public $client;
    public function __construct()
    {
        $consulConfig = Config::get('common.consul');
        $this->httpUrl = $consulConfig['host'].":".$consulConfig['port'];
        $this->client = new \GuzzleHttp\Client();
    }

    //服务注册
    public function registerService($data)
    {
        $url = $this->httpUrl.'/v1/agent/service/register';
        echo $url;
        $response = $this->client->put($url,[
           'json'=>$data
        ]);
        // 获取响应状态码
        $statusCode = $response->getStatusCode();
        // 获取响应内容
        $body = $response->getBody()->getContents();
        return $response;
    }

    //服务信息
    public function InfoService($serviceID)
    {
        $url = $this->httpUrl."/v1/health/service/".$serviceID;
        var_dump($url);
        $response = $this->client->get($url);
        return $response;
    }

    //服务配置
    public function configService($key)
    {
//        $url = $this->httpUrl.'/v1/kv/'.$key;
//        echo $url;
//        return $this->client->get($url);
        $url = $this->httpUrl . '/v1/kv/' . $key;

        $response= $this->client->get($url);
        return $response;

    }

}

controller层

<?php
namespace app\controller;

use app\BaseController;

class Consul extends BaseController
{
    private $serviceID = 'rxService';

    public function register()
    {
        $data = [
            'ID' => $this->serviceID,
            'Name' => 'rxservice',
            'Tags' => ['Core.rx'],
            'Port' => 8087,
            'Check' => [
                'HTTP' => 'http://127.0.0.1:8081',
                'Interval'=> '5s'
            ]
         ];
        $consul = new \app\service\Consul();
        $result =  $consul->registerService($data);
    }

    public function info()
    {
        $consul = new \app\service\Consul();
        $result = $consul->InfoService($this->serviceID);
        $body = $result->getBody()->getContents();
        var_dump($body);
    }
    public function config()
    {
        $consul = new \app\service\Consul();
        $result = $consul->configService($this->serviceID.'/dev/db1');

        $body = $result->getBody()->getContents();
        var_dump($body);
    }
}
# common/config.php
<?php
return [
    'consul' =>[
        'host' => "http://127.0.0.1",
        "port"=> 8500
    ]
];

你可能感兴趣的:(consul,chrome,前端)