有没有办法从我的 Express 服务器上使 Cloud CDN 上的缓存内容失效/清除?
例如,如果我正在生成服务器渲染的内容以使其易于使用,并且我从我的网站更新特定路线,例如编辑
blogPost
。我需要执行以下操作:
export const editBlogPostHandler = (req,res,next) => {
// 1. UPDATE BLOGPOST WITH SLUG some-blogpost-slug ON DB
// 2. INVALIDATE /some-blogpost-slug ROUTE ON CLOUD CDN CACHE
// THIS IS NECESSARY FOR NEW REQUESTS TO GET FRESH DATA RATHER THAN A STALE DATA RESPONSE
};
我如何从我的 Express 服务器上做到这一点?
您可以通过以下方法使 Cloud CDN 中的缓存内容失效:
gcloud
SDK:有一个 API 端点: https://cloud.google.com/compute/docs/reference/rest/v1/urlMaps/invalidateCache
POST https://compute.googleapis.com/compute/v1/projects/{project}/global/urlMaps/{resourceId}/invalidateCache
作为对 Alexandre 接受的答案的补充,以下是有关如何使用此端点的更多详细信息:
POST https://compute.googleapis.com/compute/v1/projects/{project}/global/urlMaps/{resourceId}/invalidateCache
为了获取
resourceId
,您可以调用这里提到的端点来获取urlMaps资源及其关联的ids
的列表。
GET https://compute.googleapis.com/compute/v1/projects/{project}/global/urlMaps
获得
resourceId
后,您还需要在请求正文中指定要使其失效的文件/文件夹的路径(通配符路径也可以):
{ "path": "/folder/file.mp4" }
id
- 如果您想查看此操作的进度,可以使用计算操作全局获取方法来查询。此外,为了避免多次运行相同的请求,建议以 UUID 的形式给出唯一的
requestId
参数(如 RFC 4122 中指定)
您可以使用
@google-cloud/compute
库。如果您在具有应用程序默认凭据设置的环境中运行,则特别方便。
我在云运行函数中运行这个确切的代码,以在将文件上传到存储桶后使文件无效:
import compute from '@google-cloud/compute';
const {UrlMapsClient} = compute
const urlMapsClient = new UrlMapsClient();
const project = '<project-id>';
const urlMap = '<url-map-name>'; //url map name is usually the same as your load balancer name
const pathToInvalidate = "/some/path/or/file.txt"
const request = {
project: project,
urlMap: urlMap,
cacheInvalidationRuleResource: { path: pathToInvalidate},
};
await urlMapsClient.invalidateCache(request)