Swoft与Consul(五) - 服务的发现

因为swoft的consul中的agent有时并不能获取到所有注册的consul服务,有的服务容器停止了consul也没有移除,
因此生产环境可以使用health健康检测接口来获取当前正常的服务。

1. 添加调用health接口

首先可以创建 app\client\swoft\app\Expansion\Agent.php

<?php
namespace App\Expansion;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Consul\Consul;
use Swoft\Consul\Response;
use Swoft\Consul\Agent as base;
/**
* @Bean()
*/
class Agent extends base
{
/**
* @Inject()
*
* @var Consul
*/
private $consul;
/**
* @return Response
* @throws ClientException
* @throws ServerException
*/
public function getService($serverName): Response
{
return $this->consul->get('/v1/health/service/'.$serverName);
}
}?>

2. 修改RpcProvider

app\client\swoft\app\Common\RpcProvider.php

<?php
namespace App\Common;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Config\Annotation\Mapping\Config;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Consul\Exception\ClientException;
use Swoft\Consul\Exception\ServerException;
use Swoft\Rpc\Client\Client;
use Swoft\Rpc\Client\Contract\ProviderInterface;
use App\Expansion\Agent;
/**
* Class RpcProvider
*
* @since 2.0
*
* @Bean()
*/
class RpcProvider implements ProviderInterface
{
/**
* @Inject()
*
* @var Agent
*/
private $agent;
/**
* @Config("consul.server_name")
*/
private $serverName;
/**
* @param Client $client
*
* @return array
* @throws ClientException
* @throws ServerException
* @example
* [
* 'host:port',
* 'host:port',
* 'host:port',
* ]
*/
public function getList(Client $client): array
{
// Get health service from consul
$services = $this->agent->getService($this->serverName);
$serviceList = json_decode($services->getBody(), true);
$address = [];
foreach ($serviceList as $k => $v) {
//判断当前的服务是否是活跃的,并且是当前想要去查询服务
foreach ($v['Checks'] as $c) {
if ($c['ServiceName'] == $this->serverName && $c['Status'] == "passing") {
$address[] = $v['Service']['Address'] . ":" . $v['Service']['Port'];
}
}
}
return $address;
}
}
?>

增加配置: app\client\swoft\config\consul.php

<?php
return [
'server_name' => 'swoft_goods_server'
];?>

3. 添加代码测试

可以在 app\client\swoft\vendor\swoft\rpc-client\src\Connection.php 加一下代码测试

<?php
namespace Swoft\Rpc\Client;
class Connection extends AbstractConnection implements ConnectionInterface
{
// ..
private function getHostPort(): array
{
// ..
$randKey = array_rand($list, 1);
var_dump($list[$randKey]);
$hostPort = explode(':', $list[$randKey]);
// ..
}
}?>

然后在访问的时候就可以看到这样的效果
QQ截图20220829141203.png

标签: consul, health

相关文章

添加新评论