範例:一般用途快取

您正在查看 Apigee Edge 說明文件。
查看 Apigee X 說明文件
資訊

您可以使用政策,將資料儲存在一般用途的快取中,加快擷取速度。您可以使用下列政策,在執行階段儲存及擷取快取資料:

這些政策旨在針對 Proxy 使用的資料進行一般快取。

本主題中的程式碼範例是以 GitHub 上的傳出 OAuth 範例 Proxy 為基礎 (請參閱範例清單)。這個範例使用快取政策來儲存 OAuth 存取權杖,以便在多項傳出呼叫中重複使用。

每個政策類型是由 XML 架構 (.xsd) 定義。歡迎參考 GitHub 的政策結構定義

在以下範例中,系統會使用 PopulateCache 政策將 OAuth 存取權杖寫入快取,LookupCache 政策為後續要求擷取 OAuth 權杖。存取權杖到期後,系統會使用 JavaScript 擷取新的存取權杖,並由 PopulateCache 政策快取這個新存取權杖。

填入快取

使用 PopulateCache 政策將資料寫入快取。這個範例會將 OAuth 存取權杖寫入快取。如需政策參考資料資訊,請參閱「填入快取政策」。

<PopulateCache name="token-cache">
    <!-- The cache to write to. -->
    <CacheResource>mycache</CacheResource>
    <!-- The source of the data, a variable containing the value. -->
    <Source>twitter-translate.apiAccessToken</Source>
    <!-- An enumeration representing a prefix for namespace scope. -->
    <Scope>Exclusive</Scope>
    <!-- A unique pointer (a flow variable value) to the data. Use this later to retrieve it. -->
    <CacheKey>
        <KeyFragment>apiAccessToken</KeyFragment>
        <KeyFragment ref="request.queryparam.client_id"></KeyFragment>
    </CacheKey>
    <!-- Entries placed into the cache with this policy will expire after 600 seconds. -->
    <ExpirySettings>
        <TimeoutInSec>600</TimeoutInSec>
    </ExpirySettings>
</PopulateCache>

可使用政策或程式碼填入變數。這個範例中的 Source 變數是由下列 JavaScript 呼叫填入:context.setVariable('twitter-translate.apiAccessToken', getAccessToken());

如要進一步瞭解快取金鑰,請參閱「使用快取金鑰」一文。

查詢快取資料

你可以使用 LookupCache 政策擷取快取值。下列 LookupCache 政策會從 mycache 讀取值,並將該值寫入 twitter-translate.apiAccessToken 變數。如需政策參考資料資訊,請參閱「LookupCache 政策」。

<LookupCache name="token-cache">
    <!-- The cache to read from. -->
    <CacheResource>mycache</CacheResource>
    <!-- Where to assign the retrieved value - here, a variable. -->
    <AssignTo>twitter-translate.apiAccessToken</AssignTo>
    <!-- An enumeration representing a prefix for namespace scope. -->
    <Scope>Exclusive</Scope>
    <!-- The unique pointer (a flow variable value) that was used to store the data in the cache. -->

    <CacheKey>
        <KeyFragment>apiAccessToken</KeyFragment>
        <KeyFragment ref="request.queryparam.client_id"></KeyFragment>
    </CacheKey>
</LookupCache>

撤銷快取

您可以指定 HTTP 標頭,明確地撤銷快取。如果收到包含指定 HTTP 標頭的要求,就會清除快取。如需政策參考資料資訊,請參閱「InvalidateCache 政策」。

<InvalidateCache name="InvalidateMyCache">
    <!-- The cache to invalidate. -->
    <CacheResource>test-cache</CacheResource>
    <!-- An enumeration representing a prefix for namespace scope. -->
    <Scope>Exclusive</Scope>
    <!-- Fragments constructing the unique pointer used when 
        the data was put into the cache. -->
    <CacheKey>
        <KeyFragment>apiAccessToken</KeyFragment>
        <KeyFragment ref="request.queryparam.client_id" />
    </CacheKey>
    <PurgeChildEntries>true</PurgeChildEntries>
</InvalidateCache>