【问题标题】:Sails JS with Redis for cachingSails JS 与 Redis 进行缓存
【发布时间】:2015-05-28 05:43:51
【问题描述】:

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

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

【问题讨论】:

    标签: api caching redis sails.js


    【解决方案1】:

    您可以使用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 - 我在我的风帆模型中使用了这段代码:- var client = redis.createClient(); client.on('connect', function() { console.log('redis connected'); }); client.set('framework', 'AngularJS'); console.log('Redis 在行动:', client.get('framework'));但我收到错误:错误:与 127.0.0.1:6379 的 Redis 连接失败 - 连接 ECONNREFUSED 127.0.0.1:6379。除了sails之外,我们还需要在我们的机器上运行redis服务器吗?我们不能只使用redis作为没有它的服务器的缓存解决方案吗?
    • Redis 必须正在运行 :)
    猜你喜欢
    • 2018-02-14
    • 2020-01-27
    • 2020-09-04
    • 2021-07-02
    • 2014-05-01
    • 1970-01-01
    • 2021-08-29
    • 2014-11-06
    • 2018-10-12
    相关资源
    最近更新 更多