一般用途快取

本頁內容適用於 ApigeeApigee Hybrid

查看 Apigee Edge 說明文件。

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

這些政策適用於 Proxy 使用的資料一般快取。

本主題的程式碼範例是以 GitHub 上的輸出 OAuth 範例 Proxy 為基礎。這個範例會使用快取政策儲存 OAuth 存取權杖,以便在多個外送呼叫中重複使用。

在下列範例中,OAuth 存取權杖是使用 PopulateCache 政策寫入快取。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 policy」。

<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>