問題描述

你會認為一個暫時的設定將在一定時間到期,直到那時才會存在。不幸的是,它似乎早已從資料庫中消失,無論是測試還是生產。作為一個簡單的例子來看這個行為,嘗試:

<?php
/*
Plugin Name: Test transient
Description: Show transients bug
Version: 0.1
*/

add_action( 'wp_head', 'doAnAlert' );

function doAnAlert()
{
    if( !get_transient( 'my_messageDismiss' ) )
    {
        //Transient nonexistent or expired
        ?><script> alert("This alert should also show again in 24hr"); </script>
        <?php

        set_transient( 'my_messageDismiss', 'dismissed', 86400); //Set for a day
    }

}

那麼我在 Transient API 中缺少什麼呢?警報顯示幾小時後,不是一天之後。

最佳解決方案

長話短說

  • WordPress 部分的瞬態處理是堅實的,一切都很精確

  • 瞬態使用物件快取代替 non-default 實現的資料儲存

  • 這意味著一些 back-end 快取系統擺脫了最近尚未被訪問的快取

  • 底線:它不是 WordPress 的錯誤,它只取決於你的 back-end 快取的設定

您可以使瞬態更準確,但需要 back-end 快取調整,如果您不知道自己在做什麼,我不建議使用此功能,因此快取可能會產生相反的影響。

但即使如此,也不要以為 100%的精確度。


來自 WordPress Codex

Everyone seems to misunderstand how transient expiration works, so the long and short of it is: transient expiration times are a maximum time. There is no minimum age. Transients might disappear one second after you set them, or 24 hours, but they will never be around after the expiration time.

你應該總是有一個倒退的方法。


為什麼會發生?

WordPress only invalidates transients when attempting to read them (which has lead to garbage collection problems in the past). However, this is not guaranteed for other backends.

Transients use the object cache for non-default implementations. The really important part to note here is that the object cache is a cache, and absolutely not a data store. What this means is that the expiration is a maximum age, not a minimum or set point.

One place this can happen easily is with Memcache set in Least Recently Used (LRU) mode. In this mode, Memcache will automatically discard entries that haven』t been accessed recently when it needs room for new entries. This means less frequently accessed data (such as that used by cron data) can be discarded before it expires.

閱讀更多從 this article,這是很好的解釋。


快取?

有很多不同的系統,但這裡是一個 MySQL 資料庫快取通用的例子。我不知道如何有助於瞭解瞬態快取,但我猜這不會傷害。

  • 來自每個不同查詢的資料被快取

  • 每個快取的資料都會獲得一個值 (更為複雜的查詢==的值越高)

  • 這些值會減少 (如倒數計時器,如果你願意)

  • 快取系統會間隔檢查這些值

  • 如果這些值中的任何值達到零,則該快取將被破壞

  • 如果相同的查詢再次執行,則值返回到初始值

那麼你可以從中得出什麼結論?沒有任何意義來設定瞬態:

  • 太簡單

  • 不常用

因為在大多數情況下這些都很快被破壞了。我希望這能給你一個更清晰的圖片快取一般如何工作。它優先於頻繁和複雜的簡單和很少使用的資料。

注意:在快取解釋中有很多概括,以使其易於遵循和理解。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。