TP6和nacos利用timer实现注册、发现、调用其他服务接口

1、下载三方类库(卫爷的包)

composer require zhwei/nacos-sdk-php

我composer没成功直接下载下来放到vender里。
2、注册发现使用类库

<?php
namespace app\controller;

use app\BaseController;
use Nacos\Models\ServiceInstance;
use Nacos\NacosClient;
use Nacos\Models\BeatInfo;
use Nacos\Models\BeatResult;
use Nacos\NacosNaming;
use Nacos\Utils\RandomByWeightSelector;
//use PHPUnit\Framework\AssertionFailedError;
include_once '../vendor/nacos-sdk-php/src/Nacos/Models/ServiceInstanceList.php';
include_once '../vendor/nacos-sdk-php/src/Nacos/Models/ServiceInstance.php';
include_once '../vendor/nacos-sdk-php/src/Nacos/Models/BeatInfo.php';
include_once '../vendor/nacos-sdk-php/src/Nacos/Models/BeatResult.php';
include_once '../vendor/nacos-sdk-php/src/Nacos/Utils/RandomByWeightSelector.php';
include_once '../vendor/nacos-sdk-php/src/Nacos/NacosClient.php';
include_once '../vendor/nacos-sdk-php/src/Nacos/NacosNaming.php';
//include_once '../vendor/nacos-sdk-php/src/Nacos/Exceptions/NacosRequestException.php';
//include_once '../vendor/nacos-sdk-php/src/Nacos/Exceptions/NacosException.php';
include_once '../vendor/guzzlehttp/guzzle/src/Client.php';


class Index extends BaseController
{
	/**
     * Content: 测试注册使用微服务//下面每一步拆卡封装即可
     * VX:chaoyue3887   991305180@QQ.COM
     * TIME: 2021/3/25 23:10
     */
    public function index()
    {
		
		//注册到nacos   启动时注册
        $client = new NacosClient('192.168.1.161', 8848);
        $instance = new ServiceInstance();
        $instance->serviceName = 'hello.world';
        $instance->ip = '192.168.1.166';
        $instance->port = 80;
        $instance->healthy = true;
        $instance->ephemeral = false;
		
		
        $success = $client->createInstance($instance);
		
        echo "success:".$success;
		
		for($i=0;$i<100;$i++){
			//传输健康状态   定时  这里测试一般十几秒服务将变成不健康状态,测试做了个循环发送健康状态
			$beat = new BeatInfo();
			$beat->ip = $instance->ip;
			$beat->serviceName = $instance->serviceName;
			$beat->port = $instance->port;
			$client->sendInstanceBeat('hello.world', $beat);
			echo "<br>";echo "<pre>";
			print_r($client);
			sleep(7);
		}
		
		
		
		//获取所有集群服务   调用使用
		$ip = "";
		$port = "";
		$list = $client->getInstanceList('base-server');
		$lists = array($list);
		foreach($list->hosts as $k=>$v){//这里服务可能有多个,list返回的是对象
			$ip = $v->ip;
			$port = $v->port;
		}
		echo $ip;
		echo "<pre>";
		$arr = $this->curl_get($ip.":".$port."/menu/all" );//HTTP请求base-server的接口
		print_r($arr);
		
		
		
		echo "<pre>";
		print_r($list);
        //self::assertTrue($success);
		
		sleep(1);

        $naming = new NacosNaming($client);
        $instance = $naming->selectOneHealthyInstance('hello.world');
        

        // test NacosNamingNotFound exception
        try {
            $naming->selectOneHealthyInstance('hello.world.not-exists');
            
        } catch (AssertionFailedError $e) {
            throw $e;
        } catch (\Throwable $e) {
            
        }

        // test NacosNamingNoAliveInstance exception
        $instance->serviceName = 'hello.another-world';
        $success = $client->createInstance($instance);
   
        $success = $client->deleteInstance($instance->serviceName, $instance->ip, $instance->port);
       
        try {
            $naming->selectOneHealthyInstance('hello.another-world');
            
        } catch (AssertionFailedError $e) {
            throw $e;
        } catch (\Throwable $e) {
            
        }
		//192.168.1.161:8233/php/hello
    }
	public function curl_get($url)
	{

		$info = curl_init();
		curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($info,CURLOPT_HEADER,0);
		curl_setopt($info,CURLOPT_NOBODY,0);
		curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($info,CURLOPT_SSL_VERIFYHOST,false);
		curl_setopt($info,CURLOPT_URL,$url);
		$output = curl_exec($info);
		curl_close($info);
		return $output;
	}
	
    public function hello()
    {
       return  "hello world";
    }
}

3、使用timer实现定时计划任务发送健康状态
下面展示一些 内联代码片

// 安装workman
composer require workerman/workerman
//撞见命令
php think make:command SelfTimer
---------------------------------------------------------------------------
//创建计划任务
class SelfTimer extends Command
{
    protected $timer;
    protected $interval = 10;
    protected function configure()
    {
        // 指令配置
        $this->setName('timer')
            ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
            ->addOption('d', null, Option::VALUE_NONE, 'daemon(守护进程)方式启动')
            ->addOption('i', null, Option::VALUE_OPTIONAL, '多长时间执行一次')
            ->setDescription('开启/关闭/重启 定时任务');
    }
    protected function init(Input $input, Output $output)
    {
        global $argv;
        if ($input->hasOption('i'))
            $this->interval = floatval($input->getOption('i'));
        $argv[1] = $input->getArgument('status') ?: 'start';
        if ($input->hasOption('d')) {
            $argv[2] = '-d';
        } else {
            unset($argv[2]);
        }
    }
    protected function execute(Input $input, Output $output)
    {

        $this->init($input, $output);
        //创建定时器任务
        $task = new Worker();
        $task->count = 1;
        $task->onWorkerStart = [$this, 'start'];
        $task->runAll();
    }
    public function stop()
    {
        //手动暂停定时器
        \Workerman\Lib\Timer::del($this->timer);
    }
    public function start()
    {
        $last = time();
        $task = [
        6 => $last, 
        10 => $last, 
        30 => $last, 
        60 => $last,
         180 => $last,
          300 => $last
          ];
        $this->timer = \Workerman\Lib\Timer::add($this->interval, function () use (&$task) {
            //可以在这里写你想要实现的功能
            echo "开始";

             //每隔2秒执行一次
           try {
                 $now = time();
                  foreach ($task as $sec => $time) {
                      if ($now - $time >= $sec) {
                        每隔$sec秒执行一次
                          $task[$sec] = $now;
                     }
                  }
              } catch (\Throwable $e) {
              }
        });
    }
    ------------------------------------------------------
    //command文件修改
    return [
    'app\api\command\SelfTimer', //修改为你的文件地址
];
//启动定时器
php think SelfTimer start
//关闭定时器
php think SelfTimer stop
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值