2. 取消服务:
app\Consul\DeregisterServiceListener.php:
namespace App\Consul;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Consul\Agent;
use Swoft\Event\Annotation\Mapping\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;
use Swoft\Http\Server\HttpServer;
use Swoft\Server\SwooleEvent;
/**
* @Listener(SwooleEvent::SHUTDOWN)
*/
class DeregisterServiceListener implements EventHandlerInterface
{
/**
* @Inject()
* @var Agent
*/
private $agent;
/**
* @param EventInterface $event
*/
public function handle(EventInterface $event): void
{
/** @var HttpServer $httpServer */
$httpServer = $event->getTarget();
$this->agent->deregisterService('order-server-01');
}
}
3. http健康检查配置:
(1). 为什么要加健康检查?
①. 不加健康检查,通过相关接口获取正常的服务地址时,也能获取到数据.
②. 但是,不加健康检查,就不知道这个服务到底可用不可用.
(2). consul没有健康检查画面:
某个服务下的Service Checks提示:“This instance has no service health checks.”
3.1 http健康检查配置方式一:
在注册服务的时候,加上健康检查器.
(1). 给consul服务访问的GET请求:
app\Http\Consul.php:
namespace App\Http;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Http\Server\Annotation\Mapping\RequestMethod;
/**
* @Controller(prefix="consul")
*/
class Consul {
/**
* @RequestMapping("health", method={RequestMethod::GET})
*/
public function health(): array
{
return ['status' => 'ok'];
}
}
(2). 在注册代码之前:
app\Consul\RegisterServiceListener.php:
$service = [
...
"Checks" =>[
[
"name" => "order-check",
"http" => 'http://192.168.33.88:8306/consul/health',
"interval" => "10s",
"timeout" => "5s"
]
]
]
注:
①. http代表以http方式检查:
a. consul服务会去访问这个接口,只要能得到正确的响应.就认为健康检查是通过的.
b. 这个地址是由本服务去提供一个GET请求(默认是GET,可以设置为POST).
②. interval表示每隔10s来检查地址.
③. 启动后,会出现以下图片画面.
3.2 http健康检查配置方式二:
沿用上面consul访问的路由,并在注册代码之后:
$this->agent->registerCheck([
"name" => "prod-check",
"http" => 'http://192.168.33.88:8306/consul/health',
"interval" => "10s",
"timeout" => "5s",
"serviceid"=>"prodservice-id-1"
]);
4. 注册两个服务:
(1). 修改服务注册代码:
app\Consul\RegisterServiceListener.php:
...
$this->agent->registerService($service);
# 为了演示,在上面代码,同一个服务器IP新增服务2(取消注册也要同步取消该节点)
$service2 = $service;
$service2['ID'] = 'order-server-02';
$this->agent->registerService($service2);
(2). 增加第二台服务注册的健康检测代码:
app\Http\Consul.php:
/**
* @RequestMapping("health2", method={RequestMethod::GET})
*/
public function health2(): array
{
return ['status' => 'ok2'];
}
(3). consul服务的显示: