【问题标题】:Using redis and node.js issue - Redis_client.hget return always false使用 redis 和 node.js 问题 - Redis_client.hget 总是返回 false
【发布时间】:2020-05-03 03:09:39
【问题描述】:

我正在运行一个由 node.js 支持的简单 Web 应用程序,我正在尝试使用 redis 存储一些密钥对 Json 对象,并将数据存储到 redis 中,因为我在“redis- cli" 控制台。但是当我尝试获取数据时,它总是返回 false 事件而没有错误。

我所做的只是在命令行上运行“node index.js”,这是我的 index.js 的前几行:

const getRedisClient = () => {
  client = redis.createClient(REDIS["PORT"], REDIS["HOST"]);
  client.on("error", function(err) {
    console.log("Redis Error " + err);
  });
  return client;
}

const getPostByLocalDbPath = (local_db_path, user_id) => {
  try {
    let client = getRedisClient();
    console.log("---- cache keys -----");
    console.log(user_id, local_db_path);
    let data = client.hget(user_id, local_db_path, function (err, obj) {
      if(err) {
        return null;
      }
      return obj;
    });
    console.log("--- cache data ---", data);
    return data;
  } catch (err) {
    console.log("--- cache get exception ---", err);
    return {};
  }
}

当我调用“getPostByLocalDbPath”方法时,它返回 false 而不是我存储在 redis 缓存中的数据。

当我跑步时

HGET 87 bdre2eb7-38b3-11e9-b66c-0af14c44c62s

redis-cli 控制台上的命令,然后我可以看到该键的数据

【问题讨论】:

标签: node.js redis node-redis


【解决方案1】:

你可以使用 Promisify:

var redis = require("redis");

const getRedisClient = () => {
  cl = redis.createClient();
  cl.on("error", function(err) {
    console.log("Redis Error " + err);
  });
  return cl;
}

let client = getRedisClient();
const {promisify} = require('util');
const hgetAsync = promisify(client.hget).bind(client);

async function getPostByLocalDbPath(local_db_path, user_id){
    console.log("---- cache keys -----");
    console.log(user_id, local_db_path);
    let data = await hgetAsync(user_id, local_db_path);
    console.log("--- cache data ---", data);
    return data;
}

getPostByLocalDbPath('bdre2eb7-38b3-11e9-b66c-0af14c44c62s', '87').then(
    val=>console.log(val)
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 2016-07-20
    相关资源
    最近更新 更多