|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace app\core\traits; |
|
4
|
|
|
|
|
5
|
|
|
use GuzzleHttp\Exception\GuzzleException; |
|
6
|
|
|
use yii\base\ErrorException; |
|
7
|
|
|
use yii\helpers\ArrayHelper; |
|
8
|
|
|
use yiier\graylog\Log; |
|
9
|
|
|
|
|
10
|
|
|
trait SendRequestTrait |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @param string $type |
|
14
|
|
|
* @param string $apiUrl |
|
15
|
|
|
* @param array $options |
|
16
|
|
|
* @return string |
|
17
|
|
|
* @throws ErrorException|GuzzleException |
|
18
|
|
|
* @throws \Exception |
|
19
|
|
|
*/ |
|
20
|
|
|
protected function sendRequest(string $type, string $apiUrl, array $options = []): string |
|
21
|
|
|
{ |
|
22
|
|
|
$data = ArrayHelper::getValue($options, 'query', []); |
|
23
|
|
|
$beginMillisecond = round(microtime(true) * 1000); |
|
24
|
|
|
try { |
|
25
|
|
|
$baseOptions = [ |
|
26
|
|
|
'query' => $data, |
|
27
|
|
|
'timeout' => 10000, // Response timeout |
|
28
|
|
|
'connect_timeout' => 10000, // Connection timeout |
|
29
|
|
|
]; |
|
30
|
|
|
$client = new \GuzzleHttp\Client(['verify' => false]); |
|
31
|
|
|
$response = $client->request($type, $apiUrl, array_merge($baseOptions, $options)); |
|
32
|
|
|
Log::info('Curl 请求服务开始', ['url' => $apiUrl, $data, (array)$response]); |
|
33
|
|
|
} catch (\Exception $e) { |
|
34
|
|
|
Log::error('Curl 请求服务异常', ['url' => $apiUrl, 'exception' => (string)$e, $data]); |
|
35
|
|
|
throw new ErrorException('Curl 请求异常:' . $e->getMessage(), 500001); |
|
36
|
|
|
} |
|
37
|
|
|
if ($response->getStatusCode() == 200) { |
|
38
|
|
|
// 记录 curl 耗时 |
|
39
|
|
|
$endMillisecond = round(microtime(true) * 1000); |
|
40
|
|
|
$context = [ |
|
41
|
|
|
'curlUrl' => $apiUrl, |
|
42
|
|
|
'CurlSpendingMillisecond' => $endMillisecond - $beginMillisecond |
|
43
|
|
|
]; |
|
44
|
|
|
Log::info('curl time consuming', [$context, $data,]); |
|
45
|
|
|
return (string)$response->getBody(); |
|
46
|
|
|
} else { |
|
47
|
|
|
Log::error('Curl 请求服务成功,但是操作失败', ['url' => $apiUrl, 'data' => $data]); |
|
48
|
|
|
throw new ErrorException('Curl 请求服务成功,但是操作失败:'); |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|