简体   繁体   English

NodeJS restify API 缓存最佳实践

[英]NodeJS restify API caching best practice

I am very new to NodeJS and I am building my first API using restify.我对 NodeJS 很陌生,我正在使用 restify 构建我的第一个 API。 I want to find out what is best practice for caching the response data - each API call must have its own cache time.我想找出缓存响应数据的最佳实践 - 每个 API 调用都必须有自己的缓存时间。

I have looked at res.cache() but that seems to be only per user request and not a global application cache.我看过 res.cache() 但这似乎只是每个用户请求而不是全局应用程序缓存。

I then looked at restify-cache but the documentation did not clearly tell me how to use it.然后我查看了restify-cache但文档没有明确告诉我如何使用它。

My application works like this:我的应用程序是这样工作的:

server.js code: server.js 代码:

var restify = require('restify');
var mysqlDB = require('./config/connection');

// REST server declaration and configuration
var server = restify.createServer({
  name: 'test-api',
  version: '0.0.1'
});

server.pre(restify.pre.sanitizePath());
server.use(restify.queryParser());
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());

server.listen(9007, function() {
  console.log('%s listening at %', server.name, server.url);
  mysqlDB.handleDisconnect();
  console.log(new Date() +': Started Cricket API on port 9007');
});

var routes = require('./routes')(server);

routes.js code:路线.js代码:

module.exports = function(app) {
app.get('/', function(req, res, next) {
    return res.send("You have reached the test API");
});

var fixtures = require('./controllers/fixtures');
    app.get('/getfixtures', fixtures.getFixtures);  // Get All Fixtures
};

fixtures.js code snippet: fixtures.js 代码片段:

this.getFixtures = function (req, res, next) {

res.header("Access-Control-Allow-Origin", "*"); 
res.header("Access-Control-Allow-Headers", "X-Requested-With");

console.log("Get All Fixtures");
var mysql = mysqlDB.getConnection();

var query = "SELECT * FROM fixtures WHERE fixture_date >= CURDATE() ORDER BY fixture_date, fixture_time";          
      mysql.query(query,function(err,rows){
        if(err) {
            var status = mysqlDB.getErrorStatus(err.code);
            return res.status(status.code).send("Error : "+ status.Message);                  
        } else {
          var data = [];
          for (i in rows){
            var item = rows[i];

            var output = util.formatDate(item.fixture_date);
            item.fixture_date = output;

            data.push(item);
          };

          return res.send(data);
        }
      });
  };

Can someone please send me in the right direction?有人可以向我发送正确的方向吗? I don't know where to add the caching part?我不知道在哪里添加缓存部分?

From the library file: server.use(cache.before);从库文件: server.use(cache.before); is a middleware that will be triggered to load before the request is handled, going to Redis and checking if the header_{url} key and payload_{url} exits, and at that case the value is returned.是一个中间件,将在处理请求之前触发加载,转到 Redis 并检查header_{url}键和payload_{url}存在,在这种情况下返回值。

You could put it as mentioned in this gist: https://gist.github.com/jeffstieler/3d84fa5468c7eadb7685你可以把它放在这个要点中提到的: https : //gist.github.com/jeffstieler/3d84fa5468c7eadb7685

var server = restify.createServer({
  name: 'test-api',
  version: '0.0.1'
});

server.pre(restify.pre.sanitizePath());
server.use(cache.before);
server.use(restify.queryParser());
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.on('after', cache.after);

In your code I would add the cache.before after you sanitize the path as this will be saved in Redis.在您的代码中,我会在您清理路径之后添加cache.before ,因为这将保存在 Redis 中。 also a next() should be included in every route cached.每个缓存的路由中也应该包含next()

I ended up using node-cache It was easy to use since I come from a Java/Play Framework background - hopefully it helps someone else in future.我最终使用了node-cache它很容易使用,因为我来自 Java/Play 框架背景 - 希望它在未来对其他人有所帮助。

Example usage:用法示例:

var nodeCache = require( "node-cache" );
var myCache = new nodeCache();

var cachedValue = myCache.get("alltests", true);

if (cachedValue != undefined) {
  return res.send(cachedValue);
} else {
  // Do work here and then:
  success = myCache.set("alltests", valueHere, cacheTime);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM