使用Redis将JS用于缓存

ble*_*204 6 api caching redis sails.js

正如我在之前的问题中所说,我正在尝试学习如何使用sails.js,我现在要做的是将api的响应缓存到redis.我已经搜索了如何做到这一点,但我不能让它工作.没有缓存,我通过ajax调用api.

有关如何使用我的控制器进行操作的任何想法?如何使用sails.js中的控制器调用api并使用redis缓存响应?

Mun*_*sim 11

您可以使用https://github.com/mranney/node_redis

脚步:

添加到package.json

"redis": "^0.12.1"
Run Code Online (Sandbox Code Playgroud)

npm install
Run Code Online (Sandbox Code Playgroud)

创建服务模块/api/services/CachedLookup.js

var redis = require("redis"),
  client = redis.createClient();

module.exports = {

  rcGet: function (key, cb) {
    client.get(key, function (err, value) {
      return cb(value);
    });
  },

  fetchApi1: function (cb) {
    var key = 'KEY'
    CachedLookup.rcGet(key, function (cachedValue) {
      if (cachedValue)
        return cb(cachedValue)
     else {//fetch the api and cache the result
        var request = require('request');
        request.post({
          url: URL,
          form: {}
        }, function (error, response, body) {
            if(error) {
               //handle error
            }
            else {
            client.set(key, response);
            return cb(response)
            }
        });
      }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

控制器内部

CachedLookup.fetchApi1(function (apiResponse) {
      res.view({
        apiResponse: apiResponse
      });
    });
Run Code Online (Sandbox Code Playgroud)