Sails JS结合Redis进行缓存

6

如我之前提到的问题,我正在尝试学习如何使用sails.js,在尝试将api的响应缓存到redis中。我已经搜索了如何做到这一点,但是我无法让它起作用。在没有缓存的情况下,我通过ajax调用api。

您有什么想法可以让我如何在控制器中调用api并使用redis缓存响应?

1个回答

11

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

步骤:

将其添加到 package.json 文件中

"redis": "^0.12.1"

运行

npm install

创建一个服务模块 /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)
            }
        });
      }
    });
  }
}

控制器内部

CachedLookup.fetchApi1(function (apiResponse) {
      res.view({
        apiResponse: apiResponse
      });
    });

@Muntasim - 我在我的 sails Model 中使用了以下代码: var client = redis.createClient();client.on('connect', function() { console.log('redis 已连接'); }); client.set('framework', 'AngularJS'); console.log('Redis 正在运行: ', client.get('framework')); 但是我遇到了错误:Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379。我们需要在机器上运行 redis 服务器吗?难道我们不能只使用 redis 作为缓存解决方案而不需要其服务器吗? - C.P.
Redis 必须在运行 :) - Muntasim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接