5. 服务调用初步封装client类:
实际开发中,对方的api是RPC、GRPC、JSONRPC、HTTP api,可以灵活的切换.
(1). swoft容器安装Guzzle:
# Install Composer
curl -sS https://getcomposer.org/installer | php
php composer.phar require guzzlehttp/guzzle
(2). client类调用http api:
app\Consul\ServiceClient.php:
namespace App\Consul;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
/**
* @Bean()
*/
class ServiceClient {
const SELECT_RAND=1;
const SELECT_IPHASH=2;
const SELECT_ROUNDROBIN=3;
/**
* @Inject()
* @var ServiceSelector
*/
private $selector;
private function loadService(array $serviceList, int $selectType)
{
switch ($selectType){
case self::SELECT_RAND:
return $this->selector->selectByRandom($serviceList);
case self::SELECT_IPHASH:
return $this->selector->selectByIPHash(ip(), $serviceList);
default:
return$this->selector->selectByRoundRobin($serviceList);
}
}
public function call($service, $endpoint, $method="GET",$selectType=ServiceClient::SELECT_ROUNDROBIN)
{
// 从consul获取服务
$getService=$this->loadService($service, $selectType);
$client = new \GuzzleHttp\Client();
// $endpoint类似/order/list,即path(http),后面$endpoint还要考虑RPC
$url = "http://" . $getService["Address"] . ":" . $getService["Port"] . $endpoint;
$response= $client->request($method, $url);
return $response->getBody();
}
}
(3). 提供一个order/list的api:
app\Http\Order.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("order")
*/
class Order {
/**
* @RequestMapping(router="list", method={RequestMethod::GET})
*/
public function list(): array
{
return ['order_list'];
}
}
(4). 访问:
http://192.168.33.88:8306/order/list得到结果是[‘order_list’].