如何使用cloudflare工作缓存作为快速KV?

问题描述 投票:0回答:1

我似乎无法按照 Cloudflare 文档中的描述让 Cloudflare 缓存正常工作 https://developers.cloudflare.com/workers/runtime-apis/cache/

我正在尝试使用 Cloudflare 工作缓存作为数据库前面的缓存层。

const CACHE_URL_PREFIX = 'https://api.example.com/';

function getCache() {
  return caches.default;
}

function generateHash(str: string) {
  let hash = 0, i, chr;
  for (i = 0; i < str.length; i++) {
    chr = str.charCodeAt(i);
    hash = ((hash << 5) - hash) + chr;
    hash |= 0;
  }
  return hash.toString(36);
}

function toUniqueUrlPath(str: string) {
  let normalizedStr = str.trim();

  normalizedStr = normalizedStr.toLowerCase();
  
  normalizedStr = normalizedStr.replace(/[^a-z0-9 -]/g, '-');
  normalizedStr = normalizedStr.replace(/\s+/g, '-'); 

  const uniqueHash = generateHash(str);

  return `${normalizedStr}-${uniqueHash}`;
}

export function getCacheKey(key: string) {
  const normalizedKey = toUniqueUrlPath(key);

  const url = (CACHE_URL_PREFIX + normalizedKey)
    .replace(/\/+/g, '/');

  return new Request(url);
}

export async function getCacheValue<T>(key: string) {
  const cache = await getCache();
  const cacheKey = getCacheKey(key);
  
  const cachedResponse = await cache.match(cacheKey);
  
  if (cachedResponse) {
    return await cachedResponse.json() as T;
  }

  return undefined;
}


export async function setCacheValue<T>(key: string, value: T, ttl: number) {
  const cache = await getCache();
  const cacheKey = getCacheKey(key);

  const response = new Response(JSON.stringify(value), {
    headers: {
      'Content-Type': 'application/json',
      'Cache-Control': `public, max-age=${ttl}`
    }
  });

  await cache.put(cacheKey, response);

  const valueFromCache = await getCacheValue<T>(key); 

  if (!valueFromCache) {
    console.error('Failed to set cache value', {
      key,
      value,
      ttl,
      url: cacheKey.url,
    });
  }
}

控制台错误“无法设置缓存值”不断出现,并且在后续请求中 getCacheValue 不返回任何内容。在过去的 3 个小时里我一直在尝试调试这个。

我的实现有什么问题吗?

caching cloudflare web-worker cache-control cloudflare-workers
1个回答
0
投票

更新。我在 Website / caching / caching-rules 中有一些适用于工作缓存的缓存规则。删除了规则现在可以正常工作了。

© www.soinside.com 2019 - 2024. All rights reserved.