我已经构建了一个基于PubNub的实时聊天应用程序。目前,我只允许通过PubNub直接向用户发送消息和从用户接收消息。但是,我希望通过以下方式“保存”这些消息:首先将它们推送到我的服务器/db(内置在PHP和MySQL中),然后在成功进入后,通过PubNub发送给用户。
我现在的服务器的设置接受该请求,并将其定向到适当的case语句,给定传递到请求中的已定义action:
<?php
switch($action)
{
case "userLogin":
...
break;
case "signUpUser":
...
break;
...
case "syncWithServer":
...
break;
?>其中,每个case语句都允许数据库插入和更新,并在给定传递的数据的情况下在操作成功时随后返回。
对于一个详细的例子,我们有下面的sendMessage案例。必须插入数据,然后返回刚刚插入的消息的最新sync_id,然后将其发送回用户,以便保持所有内容同步:
case "sendMessage":
// Output is: {"message_sync_id":"4"}
if ($userId = authenticateUser($db, $username, $password, $gcmregid))
{
//echo "passed1";
if (isset($_REQUEST['to_user_sync_id']))
{
//echo "passed2";a
$touserid = $_REQUEST['to_user_sync_id'];
$unescapedMessage = $_REQUEST['message_text'];
$message = mysql_real_escape_string($unescapedMessage);
$campaign = $_REQUEST['shared_campaign_id'];
$location = $_REQUEST['shared_campaign_location_id'];
if($stmt1 = $db->prepare("INSERT INTO `messages` (`message_sync_id`,`from_user_sync_id`, `to_user_sync_id`, sent_dt, `message_text`,`shared_campaign_id`,`shared_campaign_location_id`)
SELECT
CASE
WHEN max(message_sync_id) is null
THEN 0
ELSE max(message_sync_id)
END + 1
, ?
, ?
, NOW()
, ?
, ?
, ?
from messages;"))
{
$stmt1->bind_param("sssss", $userId,$touserid,$message,$campaign,$location);
$stmt1->execute();
$stmt1->close();
$sqlMaxSyncId = "select max(message_sync_id) as message_sync_id from messages;";
if($resultMaxID = $db->query($sqlMaxSyncId))
{
$row = $resultMaxID->fetch_assoc();
$out = json_encode(array('message_sync_id' => $row['message_sync_id']));
error_log("sendMessage", 3 , $row['message_sync_id']);
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
break;鉴于聊天应用程序需要非常低的延迟,这个公式可能会遇到哪些生产问题,而我在非常低的使用率测试中可能看不到这些问题?
如何缓解这些问题呢?
Heroku是部署这种服务器的合适环境吗?
发布于 2016-02-18 00:40:09
如果许多用户同时在聊天,那么保存到数据库(我猜是"syncWithSErver")可能会成为瓶颈,因为我猜测,case语句执行数据库查询,数据库将会超载,从而减慢消息分派。
不是直接保存它们,而是使用任何内存缓存,如memcache或redis来临时存储它们,并使用后台作业(例如,附加到cron的php脚本)来持续保存它们。
https://stackoverflow.com/questions/35460343
复制相似问题