對於你的問題:
我如何獲得MySQL告訴Memcached的導致對某個查詢 已經改變,一個表不應來自緩存在下一次 被加載,而是來了從數據庫中並因此更新 的緩存?
當數據更新(或等到它過期)時,您需要清除緩存。
Memcache是一個關鍵存儲...所以你需要一個唯一的鍵代表你試圖檢索的數據。
例如,假設您有與博客文章相關的查詢。一個唯一的ID將是你的帖子ID或它的頁面url/slug。
所以你通常做的是在做數據庫查詢之前,檢查Cache中是否有存儲的版本。
$memcache = new Memcache();
$memcache->connect('localhost', 11211) or die ("Could not connect");
$postId = 1234; // this would vary between each posts.
$commentsKey = 'comments_'. $postId;
$result = $memcache->get($commentsKey);
if ($result === false) { // key not found
// only fetch when result are NOT in cache
$pdo = new PDO();
$stmt = $pdo->query("SELECT * FROM comments WHERE postId=". $pdo->quote($postId));
$result = $pdo->fetchAll();
// store it for next time
$memcache->set($commentsKey, $result);
} //if
// use result either from cache or database
foreach ($result as $comment) {
// do something with data
}
而且重置緩存(或無效的話),你可以清除評論鍵時,有人張貼新評論...
$memcache = new Memcache();
$memcache->connect('localhost', 11211) or die ("Could not connect");
$postId = 1234; // this would vary between each posts.
$commentsKey = 'comments_'. $postId;
$memcache->delete($commentsKey);
// OR
$memcache->set($commentsKey, false);
這樣,下次用戶retreives評論將有
將其從數據庫中取出而不是緩存,因爲$ result將是錯誤的。
MySQL查詢緩存將已經緩存查詢的結果集。但是,只要表得到更新,緩存的結果集就會失效。所以,我想用Memcached緩存特定的結果集仍然是一個很好的用例。您是否正在使用可能具有使用Memcached的API的框架? – dcarrith
如果您使用的是Laravel框架,那麼這個問題將很容易解決。一般來說,爲了回答你的問題,你需要使用每個用戶唯一的密鑰緩存一個特定的結果集(也許某些值與user_id連接)。如果某個特定用戶存在緩存記錄,則可以從緩存中加載。否則,您將運行查詢並緩存結果集。然後,對於負責更新主查詢中使用的任何表的任何頁面,您都可以通過使用基於user_id的唯一鍵來使緩存記錄無效。 – dcarrith