在webman控制器中使用http-client由于无法将请求第三方接口的响应,响应给前端,所以我参考了https://www.workerman.net/q/9562
我的下面的代码是一个请求tts的接口,然后将音频数据返回给前端,我现在有一个问题就是自定义进程中的异步请求是如何实现给前端响应的呢?我总是有一种同步的错觉,还有就是,如果请求耗时,是否会影响下一次请求呢?
<?php
namespace app;
use support\Response;
use Workerman\Connection\TcpConnection;
use Workerman\Http\Client;
use Workerman\Protocols\Http\Request;
class Api
{
public function onMessage(TcpConnection $connection, Request $request)
{
$text=$request->post("text");
//if ($request->path() == '/test/test') {
$options = [
'max_conn_per_addr' => 128, // 每个地址最多维持多少并发连接
'keepalive_timeout' => 15, // 连接多长时间不通讯就关闭
'connect_timeout' => 30, // 连接超时时间
'timeout' => 30, // 等待响应的超时时间
];
$http = new Client($options);
$http->request('/v1/audio/speech', [
'method' => 'POST',
'version' => '1.1',
'headers' => ['Connection' => 'keep-alive'],
'data' => json_encode(["input"=>$text,"model"=>"tts-1","voice"=>"zh-CN-XiaoxiaoNeural"]),
'success' => function ($response)use($connection,$request) {
$res=new Response(200,[
'Content-Type' => 'audio/mpeg',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Origin' => $request->header('origin', '*'),
'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
],$response->getBody());
$connection->send($res);
},
'error' => function ($exception) {
echo $exception;
}
]);
return;
// }
// $connection->send(response('404 not found'), 404);
}
}
代码应该就是类似你这样写就行
代码是没什么问题,我测试了下这样写的性能,比fpm的curl速度还慢,然后发现在控制器里用chunk流式响应音频文件竟然也可以,性能很棒