我知道memcached是如何工作的。您使用它来存储数据块以提高站点性能。当你想检索一些数据时,先检查它是否在memcached中,如果是,则检索它,否则检查数据库/文件系统等。
我只是不知道如何/何时使用它?什么是好机会?
我有以下表格:
作者:
id username email password salt email_salt email_verified IP_ADDRESS
Author_threads:
thread_id,author_id
主题:
id,title,content,created
标签:
id,name
Thread_tags:
tad_id,thread_id
我想选择最新的30个主题,他们的作者及其所有标签。这是我使用的SQL语句:
SELECT thread.title, thread.id as thread_id,
thread.content, author.username, author.id as author_id,
GROUP_CONCAT(DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',') AS tags
FROM thread
JOIN thread_tags ON thread.id = thread_tags.thread_id
JOIN tag ON thread_tags.tag_id = tag.id
JOIN author_threads ON thread.id = author_threads.thread_id
JOIN author ON author_threads.author_id = author.id
GROUP BY thread.id DESC
LIMIT 0, 30
这是我使用的PHP:
function get_latest_threads($link, $start)
{
$start = minimal_int($start);
$threads = sql_select($link, "SELECT thread.title, thread.id as thread_id,
thread.content, author.username, author.id as author_id,
GROUP_CONCAT(DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',') AS tags
FROM thread
JOIN thread_tags ON thread.id = thread_tags.thread_id
JOIN tag ON thread_tags.tag_id = tag.id
JOIN author_threads ON thread.id = author_threads.thread_id
JOIN author ON author_threads.author_id = author.id
GROUP BY thread.id DESC
LIMIT $start, 30" # I only want to retrieve 30 records each time
);
return $threads;
}
memcached在哪里/如何在这里使用?
答案 0 :(得分:9)
我只是不知道如何/何时使用它?
只有在证明后才能使用它,即添加缓存可以获得最佳性能提升。将数据缓存或输出缓存添加到以前没有任何缓存的复杂应用程序可以发现大量微妙的错误和奇怪的行为。
Use a code profiler first。找出您的代码存在真正的性能问题的位置。找出瓶颈并解决它们。如果该修复涉及缓存,那么就这样,但首先收集证据。
答案 1 :(得分:1)
许多网站用户可能会请求最新线程列表,因此使用memcached缓存整个SQL结果听起来是一个绝佳的机会。
memcached的一个非常简单的方法是使用SQL查询作为键,并将它们各自的结果用作值(i.e. see this tutorial here)。您可能希望首先对所有高频数据库查询进行尝试,然后在开始进一步优化之前对结果进行概要分析。
答案 2 :(得分:1)
没有关于何时使用它的设定指南。您必须弄清楚哪些数据库查询最频繁和/或成本最高,并缓存这些查询。在你的情况下,我可能会缓存该函数调用的结果。
我会感到困惑(如你所知)是在创建新线程时做的事情。每当有人创建一个线程时,您的查询将给出不同的结果。那么在这种情况下,当有人创建线程时,您应该做的是更新数据库,然后通过踢出最旧的线程并添加新线程来调整缓存中的结果集。您甚至不需要从缓存重新加载最新的30个线程,因为它将被更新。