我正在尝试将缓存功能添加到nodejs。
我想要这样的代码,
app.get('/basement/:id', cache, (req,res) => {
client.set('basement' + req.params.id,'hello:'+req.params.id)
res.send('success from source');
});
function cache(req,res,next) {
console.log('Inside mycache:' + req.params.id);
client.get('basement' + req.params.id, function (error, result) {
if (error) {
console.log(error);
throw error;
} else {
if(result !== null && result !== '') {
console.log('IN Cache, fetching from cache and returning it');
console.log('Result:' + result);
res.send('success from cache');
} else {
console.log('Not in Cache, so trying to fetch from source ');;
next();
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
我想将一个名为cache的中间件函数应用于/ basement /:id路由收到的请求。
缓存功能将接收密钥作为其参数。在缓存内部,我想检查缓存是否存在,如果是,则从那里返回它,否则,我想调用实际的路由处理程序。密钥基于一个或多个请求参数。
这样,我最终将为我的应用程序中的每个处理程序编写一个单独的缓存功能。
我的缓存功能内部的逻辑是对该键的一般期望,该键基于实际的请求对象,并且因方法而异。
因此,我想拥有一个通用的缓存功能,该功能可以将键作为参数,这样我就可以拥有这样的代码,
app.get('/basement/:id', cache, (req,res) => {
client.set('basement' + req.params.id,'hello:'+req.params.id)
res.send('sucess from source');
});
Run Code Online (Sandbox Code Playgroud)
我的意思是我将把缓存键传递给缓存功能。因此,缓存功能可以是通用的。
但是,如果我更改如下所示的缓存功能以便接收缓存密钥,则它将不起作用。
function cache(cachekey,req,res,next) {
}
Run Code Online (Sandbox Code Playgroud)
似乎我的缓存函数中无法包含另一个参数来接收传递的参数。
我想将缓存键作为参数传递给函数。
如果有人遇到过类似的问题,请您帮我一下。
但是,如果我更改如下所示的缓存功能以接收缓存密钥,则它将不起作用。
你不能因为它不是一个有效的快递中间件(它实际上是一个错误的中间件),明确将通过:req,res,next的顺序。并且err,req,res,next错误中间件。
您的缓存function将需要返回一个中间件,因此您可以向其传递密钥。
我想创建一个通用缓存功能,该功能可以使用任何缓存键。在这种情况下,它是id,但其他情况下可能具有不同的密钥
function cache(key, prefix = '') {
// Or arrange the parameters as you wish to suits your needs
// The important thing here is to return an express middleware
const cacheKey = prefix + req.params[key];
return (req, res, next) => {
console.log('Inside mycache:' + cacheKey);
client.get(cacheKey , function(error, result) {
if (error) {
console.log(error);
return next(error); // Must be an error object
}
if (result !== null && result !== '') {
console.log('IN Cache, fetching from cache and returning it');
console.log('Result:' + result);
return res.send('success from cache');
}
console.log('Not in Cache, so trying to fetch from source ');;
next();
});
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以像这样使用它:
app.get('/basement/:id', cache('id', 'basement'), (req, res) => { /* ... */ });
app.get('/other/:foo', cache('foo', 'other'), (req, res) => { /* ... */ });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2440 次 |
| 最近记录: |