本頁適用於 Apigee 和 Apigee Hybrid。
查看
Apigee Edge 說明文件。
您可以使用政策將資料儲存在通用快取中,以便更快擷取。使用下列政策,快取代理程式就能在執行階段儲存及擷取快取資料:
- 填入快取政策,將資料新增至快取。
- LookupCache 政策:存取快取資料。
- InvalidateCache 政策,以便清除快取。
這些政策的設計目的,是針對 Proxy 使用的資料進行一般快取。
本主題的範例程式碼是以 GitHub 上的 Outbound OAuth 範例 Proxy 為基礎。這個範例會使用快取政策來儲存 OAuth 存取權權杖,以便在多個外出呼叫中重複使用。
在下列範例中,系統會使用 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>