如何简单地处理(非常)短的 mysql 复制延迟
我有一个使用 MySQL 5.5(1 个主站和 1 个从站)运行的应用程序(php),
我用它来调度主站/从站上的读/写。
当我创建新记录(用户或类似的东西)时,我将其写入主记录,当我重新加载页面时,我从从记录加载它。
示例:
...
if ($_GET['id'])
{
#Load user
$user = $sql->load('user', $_GET['id']);
if ($user == false)
{
throw exception('User not found');
}
}
else if ($_POST['create]')
{
#Create a new user
$user_id = $sql->insert('user', $_POST);
$mvc->reload('?id=' . $user_id);
exit();
}
...
但是当主服务器真正高性能(快速插入)而复制性能不佳(滞后= 0.3 - 1秒)时,重新加载将不起作用......
处理该问题的最佳实践是什么
一些解决方案:
- 数据库优化以减少 阅读之前或写作之后的滞后(非常困难)
- 睡眠(1)......不是很优雅
I have an application (php) running with MySQL 5.5 (1 master and 1 slave)
I use to dispatch read/write on master / slave.
When I create a new record (a user or something like that) I write it on the master and when I reload the page, I load it from the slave.
Example:
...
if ($_GET['id'])
{
#Load user
$user = $sql->load('user', $_GET['id']);
if ($user == false)
{
throw exception('User not found');
}
}
else if ($_POST['create]')
{
#Create a new user
$user_id = $sql->insert('user', $_POST);
$mvc->reload('?id=' . $user_id);
exit();
}
...
But when the master is really performant (quick insert) and the replication is not (lag = 0.3 - 1 sec), the reload will not work...
What are the best practice to handle that
Some solutions:
- Database optimisation for reducing the lag (very difficult)
- sleep(1) before reading or after writing ... not very elegant
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您需要定义您的应用程序是否可以处理延迟。
如果没有,那么您需要确保您想要获取的数据已经在从属设备上可用。例如从slave获取最后一个id并将其与您要获取的id进行比较;或者首先尝试从属,如果行不存在,则回退到主控(但这将使主控因请求新数据而过载)。
通常 Web 应用程序可以使用过时的数据。如果其他访问者在 10 秒后看到新帖子也没有问题。但正如您提到的,如果帖子的作者没有立即看到它,那就不好了。因此,您可以根据要获取的数据/原因采取不同的行动(例如,缓存有关会话中最近帖子的信息,在这种情况下从主服务器获取)
First, you need to define if your application can work with a lag or not.
If not, then you need to ensure that the data you want to fetch are already available on slave. For example fetch the last id from slave and compare it with id you are about to fetch; or try slave first and if row is not there, fallback to master (but that will overload the master with requests for new data).
Usually web application can work with stale data. There is no problem if other visitors will see a new post 10 seconds later. But as you mentioned, it is bad if author of the post doesn't see it immediately. So you can act differently based on the data/reason you are fetching (for example cache the info about recent post in session and in that case fetch from master)