使用AWS API网关提供的缓存失效机制,以确保缓存在数据发生变化时及时失效并更新。具体过程如下:
在API网关设置中启用缓存功能
针对需要缓存的资源,设置缓存键和过期时间,例如:
{
"methodResponses": [{
"statusCode": "200",
"responseParameters": {
"method.response.header.Cache-Control": true
},
"responseModels": {
"application/json": "Empty"
}
}],
"cacheKeyParameters": ["method.request.path.petId"],
"cacheNamespace": "pets",
"responseModels": {
"application/json": "Empty"
},
"passthroughBehavior": "when_no_match",
"type": "MOCK"
}
var apigateway = new AWS.APIGateway();
var params = {
"domainName": "api.example.com",
"stage": "prod",
"cacheKeyParameters": ["pets/123"]
};
apigateway.invalidateCache(params, function(err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});