将每个服务的 client 改为单例,修正重入问题

This commit is contained in:
George Xie 2018-06-22 20:21:08 +08:00
parent 5aaeaa0499
commit 6c54737d13
2 changed files with 12 additions and 26 deletions

View File

@ -5,25 +5,15 @@ namespace PdInternalApi;
class Client
{
protected $currentApp;
protected $service_name;
protected $config;
public function __construct($config)
public function __construct($service_name, $config)
{
$this->service_name = $service_name;
$this->config = $config;
}
/**
* @param $app
* @return $this
*/
public function app($app)
{
if (isset($this->config[$app]))
$this->currentApp = $app;
return $this;
}
/**
* 调用api如果状态码不为200则抛出异常
* @param $uri
@ -33,8 +23,7 @@ class Client
*/
public function call($uri, $params)
{
$config = array_merge(['timeout' => 3],
$this->config[$this->currentApp]);
$config = array_merge(['timeout' => 3], $this->config);
$secret = $config['secret'];
unset($config['secret']);
$client = new \GuzzleHttp\Client($config);
@ -42,10 +31,10 @@ class Client
$params['timestamp'] = time();
$params['sign'] = sign($params, $secret);
$resp = $client->post($uri, ['form_params' => $params]);
if ($resp->getStatusCode() == 200) {
return \GuzzleHttp\json_decode($resp->getBody(), true);
if ($resp->getStatusCode() != 200) {
return false;
}
return false;
return \GuzzleHttp\json_decode($resp->getBody(), true);
}
}
}

View File

@ -12,14 +12,11 @@ class ServiceProvider extends \Illuminate\Support\ServiceProvider
public function register()
{
$this->app->configure('internal_api');
$this->app->singleton('internal.api', function () {
return new Client(config('internal_api.client'));
});
foreach (config('internal_api.client') as $key => $config) {
$this->app->singleton('internal.api.' . $key, function () use ($key) {
return $this->app['internal.api']->app($key);
foreach (config('internal_api.client') as $service_name => $config) {
$this->app->singleton('internal.api.' . $service_name, function () use ($service_name, $config) {
return new Client($service_name, $config);
});
}
}
}
}