PHP接入consul,注册服务和发现服务【学习笔记】

PHP接入consul,注册服务和发现服务

consul安装

链接: consul安装

启动consul

C:\Users\14684>consul agent -dev

在这里插入图片描述

安装TP5

composer create-project topthink/think=5.0.* tp5_pro --prefer-dist

配置consul

在这里插入图片描述

创建tp5_pro/application/service/Consul.php

<?php
/*************************************************************************
 * File Name: Consul.php
 * Author: shijie.zheng
 * Created Time: 2024/7/21 18:11
 * Desc:
 ************************************************************************/

namespace app\service;


use think\Config;

class Consul
{
    private $httpUrl;

    public function __construct()
    {
        $consulPort = \think\Env::get('consul.port');
        $consulHost = \think\Env::get('consul.host');
        $this->httpUrl = 'http://' . $consulHost . ':' . $consulPort . '/';
    }

    //服务注册
    //agent/service/register
    public function registerService($data){
        $url = $this->httpUrl . 'v1/agent/service/register';
        return $this->curlPUT($url, $data);
    }
    //服务信息
    public function serviceInfo($serviceId){
        $url = $this->httpUrl . 'v1/health/service/' . $serviceId;
//        echo $url;
//        return $this->makeRequest($url);
       return file_get_contents($url);
    }

    public function curlPUT($httpUrl, $data){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$httpUrl);
        curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"PUT");
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch,CURLOPT_HTTPHEADER, ["Content-type:application/json"]);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($data));
        $res = curl_exec($ch);
        if($res === false){
            var_dump(curl_error($ch));
        }
        curl_close($ch);
        return $res;
    }

    public function makeRequest($url, $argument = array(), $ttl = 5, $method = "GET", $cookie = '', $follow = 0, $referer = '')
    {

        if (!$url) {
            throw new LogicException('$url不能为空');
        }

        if (substr($url, 0, 7) != 'http://' && substr($url, 0, 8) != 'https://') {
            return array('result' => NULL, 'code' => '400');
        }
        if ($method == 'GET' && count($argument) > 0) {
            $url .= "?" . (http_build_query($argument));
            //echo $url;
        }
        $header = array(
            'Accept-Language: zh-cn,zh;q=0.8',
            'Connection: Keep-alive',
            'Cache-Control: max-age=0'
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $argument);
        }
        if (file_exists($cookie)) {
            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
        }

        if (!empty($referer)) {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $ttl);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1707.0 Safari/537.36');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //curl_setopt($ch, CURLOPT_REFERER, 'https://analytics.talkingdata.net/webpage/UserRetainInfo.jsp');
        if ($follow == 1) {
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        }
        $return = array();
        $return['result'] = curl_exec($ch);
        $return['code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        unset($ch);
        return $return;
    }


}

创建tp5_pro/application/index/controller/ConsulDemo.php

<?php
/*************************************************************************
 * File Name: ConsulDemo.php
 * Author: shijie.zheng
 * Created Time: 2024/7/21 22:30
 * Desc:
 ************************************************************************/

namespace app\index\controller;



use app\service\Consul;

class ConsulDemo
{
    //注册服务
    public function regDemo(){
//        echo 1;
        $data = [
            'ID' => 'demoService',
            'Name' => 'demoService',
            'Tags' => ['core.demo'],
            'Address' => '127.0.0.1',
            'Port' => 8300,
            'Check' => [
                'HTTP' => 'http://127.0.0.1:80',
                'Interval' => '5s'
            ]
        ];
        $consul = new Consul();
        $rs = $consul->registerService($data);
        var_dump($rs);
    }
    //服务发现
    public function serviceInfo(){
        $serviceId = 'demoService';
        $consul = new Consul();
        $rs = $consul->serviceInfo($serviceId);
        echo $rs;
    }
}

创建路由tp5_pro/application/route.php

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
use  \think\Route;

Route::get('consul/reg/demo', 'ConsulDemo/regDemo');
Route::get('consul/service/info', 'ConsulDemo/serviceInfo');
Route::get('/test',function(){
    return 'Hello,world!';
});

浏览器进行服务注册

在这里插入图片描述

打开consul

http://127.0.0.1:8500/ui/dc1/services
在这里插入图片描述

获取信息

http://www.tp5.com/index.php/consul/service/info
在这里插入图片描述

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值