node.js - 使用redis和node.js问题-Redis_client.hget返回总是false

标签 node.js redis node-redis

我正在运行一个由node.js支持的简单网络应用程序,我尝试使用redis来存储一些 key 对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 控制台上运行命令,然后我可以看到该键的数据

最佳答案

您可以使用 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)
);

关于node.js - 使用redis和node.js问题-Redis_client.hget返回总是false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59766857/

相关文章:

javascript - "npm install -g bigcommerce-stencil/stencil-cli"无法在 Windows cmd 提示符下成功运行

Redis:计算 Redis 集群上特定类别的键?

python - redis 在我的 python django 应用程序中不工作

typescript - 在 Jest 测试中调用 new class() 后没有创建新的类实例

javascript - 管理 Node.js Redis 客户端中的唯一哈希键

node.js - 如何在NodeJS中发送包含多部分/相关数据的HTTP响应

node.js - Shibboleth 与 Node.js Rest API 和 Angular 2 应用程序

javascript - 从异步回调函数将对象推送到本地数组

redis - 仅在尚未设置时才设置原子

node.js - 错误 : connect EADDRNOTAVAIL while processing big async loop