PHP如何处理多个请求? [英] How to handle multiple requests in PHP?

查看:47
本文介绍了PHP如何处理多个请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码在 php 中创建一个简单的电报机器人:

I'm using the below code to make a simple telegram bot in php:

$message = json_decode(file_get_contents('php://input'), true);
// if it's not a valid JSON return
if(is_null($message)) return;
$endpoint = "https://api.telegram.org/bot<token>/";

// make sure if text and chat_id is set into the payload
if(!isset($message["message"]["text"]) || !isset($message["message"]["chat"]["id"])) return;

// remove special characters, needed for the interpreter apparently
$text = $message["message"]["text"];
//$text = str_replace(["\r", "\n", "\t"], ' ', $text);
// saving chat_id for convenience
$chat_id = $message["message"]["chat"]["id"];

// show to the client that the bot is typing 
file_get_contents($endpoint."sendChatAction?chat_id=".$chat_id."&action=typing");
file_get_contents($endpoint."sendMessage?chat_id=".$chat_id."&text=hi");

但问题是同时响应多个请求.用户没有实时收到响应(延迟).我确定最后一行会导致延迟并等待电报服务器的响应.我怎样才能弄清楚?

But the problem is responding to multiple requests in same time. Users aren't receiving responses in real time (delay). I'm sure that the last line causes the delay and waits for respond of telegram servers. How can I figure out that?

更新我找到了这段代码,但它仍然有延迟:

Update I found this code but it still has delay:

$ch = curl_init();
    $curlConfig = array(
        CURLOPT_URL => 'https://api.telegram.org/bot<token>/sendMessage',
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true); 
    $curlConfig[CURLOPT_POSTFIELDS] = "chat_id=".$chat_id."&text='hi'";
    curl_setopt_array($ch, $curlConfig);
    $result = curl_exec($ch);
    curl_close($ch);

问题出在哪里?

推荐答案

AS 在评论中说你可以使用一个简单的打印语句在每个命令之后输出(记录)一个时间戳.通过查看差异,您可以了解每个命令花费的时间.这应该足以确定一个简单函数中的耗时步骤.

AS said in the comments you can use a simple print statement to output (log) a timestamp after each command. By looking at the differences you see how long each command took. That should be enough jsut to identify the time consuming step in a simple function.

另一种方法是使用分析器.XDebug 有一个内置的.但是你必须设置它,我怀疑仅仅为了找出哪一步需要这么长时间......

An alternative would be to use a profiler. XDebug has one built in. But you have to set that up, I doubt that is justified just to find out which step takes so long...

然而,在我看来,最优雅的想法是在 php 中使用一个鲜为人知的特性:滴答 ;-)

However the most elegant idea in my eyes is to use a little known feature in php: ticks ;-)

这允许注册一个tick"函数一次,并在执行每个命令时自动输出一个tick.这使您不必弄乱您的代码.文档给出了一个很好的例子.

This allows to register a "tick" function once and have automatically output a tick with each command executed. This saves you from having to mess your code. The documentation gives a good example.

这篇关于PHP如何处理多个请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆