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
    ]
];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值