1. 服务发现:
上面服务注册好后,为了演示,服务自己发现自己(即自已调用自己).
(1). 获取所有服务列表:
app\Http\MyClient.php:
namespace App\Http;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Consul\Agent;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Http\Server\Annotation\Mapping\RequestMethod;
/**
* @Controller(prefix="client")
*/
class MyClient {
/**
* @Inject()
* @var Agent
*/
private $agent;
/**
* @RequestMapping(route="services", method={RequestMethod::GET})
*/
public function getServices()
{
// 通过agent获取当前服务有多少个
$services = $this->agent->services();
// 因为上面返回的是Response,所以,直接用getResult()取结果.
return $services->getResult();
}
}
注:
①. 点击$this->agent->services()方法,跳到agent类,可以看到是通过consul服务去请求这个地址,得到响应值.
②. getServices()方法返回的数据与上面在consul服务请求的响应值是一样的.
(2). agent类services方法:
vendor\swoft\consul\src\Agent.php:
public function services(): Response
{
return $this->consul->get('/v1/agent/services');
}
(3). consul服务获取所有节点列表:
http://192.168.33.88:8500/v1/agent/services
{
"order-server-01":
{"ID":"order-server-01","Service":"order","Tags":["http"],"Meta":{"version":"1.0"},"Port":8306,"Address":"192.168.33.88","Weights":{"Passing":10,"Warning":1},"EnableTagOverride":false},
"order-server-02":
{"ID":"order-server-02","Service":"order","Tags":["http"],"Meta":{"version":"1.0"},"Port":8306,"Address":"192.168.33.88","Weights":{"Passing":10,"Warning":1},"EnableTagOverride":false}
}
注:
①. 这里是获取所有的服务列表,不管理成功或失败的.
②. key-value形式.