示例:通用缓存

您正在查看的是 Apigee Edge 文档。
转到 Apigee X 文档
信息

您可以使用政策将数据存储在通用缓存中,以加快检索速度。通过使用以下政策,代理可以在运行时存储和检索缓存的数据:

这些政策旨在对您的代理使用的数据进行常规缓存。

本主题中的示例代码基于 GitHub 上的出站 OAuth 示例代理(请参阅示例列表)。此示例使用缓存政策来存储 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>