For long polling scenarios, which are more common, the client synchronizes constantly in a synchronous request, and the server decides whether to respond to requests or hold requests to continue checking the data.
Since PHP-FPM is single process single-threaded, a process can handle only one request at a time, so for this long polling scenario, a particularly large number of php-fpm processes are needed to handle high concurrency, which is particularly wasteful because most requests are hold on the server.
Now we use Openresty to poll PHP-FPM,PHP-FPM will be processed quickly, will not hold live, reduce the php-fpm pressure, the configuration file is as follows:
Location ~/longpolling (/.*) {
Content_by_lua_block {
Local Request_uri_without_args = Ngx.re.sub (Ngx.var.request_uri, "\ \"). *", "")
Request_uri_without_args = Ngx.re.gsub (Request_uri_without_args, "/longpolling", "")
Local URL = {Request_uri_without_args}
Local args = Ngx.req.get_uri_args ()
Local query = Ngx.encode_args (args)
If query ~= "" Then
url[#url + 1] = "?"
url[#url + 1] = Query
End
url = table.concat (URL)
For i = 1, 3 do
Local sleep = 1
Local res = ngx.location.capture (URL)
For K, V-pairs (res.header) do
If Type (v) = = "Table" Then
if k = = ' sleep ' and V = = 0 Then
Ngx.header[k] = Table.concat (V, ",")
Sleep = Table.concat (V, ",")
End
Else
if k = = "Sleep" and V = = "0" Then
Ngx.header[k] = V
Sleep = V
End
End
End
if sleep = = 1 Then
Ngx.sleep (1)
Else
Ngx.say (Res.body)
Break
End
End
}
}
Converts a request that starts with "longpolling" in the URL to a long poll. For example:/longpolling/aa actual access is/AA. Long polling total time is 3 seconds, each stop for one second, based on PHP-FPM response head sleep to determine whether to output or continue polling. The PHP code is as follows.
<?php
Header (' Content-type:application/json ');
$time = $_get["Time";
$data = Get_new_data ($ Time);
if ($data) {
header (' sleep:0 ');
echo Json_encode (Array ("Data" => $data));
}else{
echo json_encode (Array ("Data" => "));
}
So we made a relatively generic optimization interface that only supports get requests.