js为Redis数据库发出HGET

js为Redis数据库发出HGET

本文介绍了如何通过Node.js为Redis数据库发出HGET/GET命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Node.js和Redis数据库.我是Redis的新手.

I am using Node.js and a Redis Database . I am new to Redis .

我正在为节点使用 https://github.com/mranney/node_redis 驱动程序.

I am using the https://github.com/mranney/node_redis driver for node.

初始化代码-

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

我尝试设置一些键值对-

I tried setting up some key value pairs -

client.hset("users:123" ,"name", "Jack");

我想知道我可以通过Node从Redis获取name参数.

I wish to know I can get the name parameter from Redis via Node .

我尝试了

var name = client.hget("users:123", "name");  //returns 'true'

但是它只是返回"true"作为输出.我想要值(即-杰克)我需要使用什么语句?

but it just returns 'true' as the output. I want the value ( i.e - Jack )What is the statement I need to use ?

推荐答案

您应该这样做:

client.hset("users:123", "name", "Jack");
// returns the complete hash
client.hgetall("users:123", function (err, obj) {
   console.dir(obj);
});

// OR

// just returns the name of the hash
client.hget("users:123", "name", function (err, obj) {
   console.dir(obj);
});

还要确保您了解JavaScript中的回调和闭包的概念以及node.js的异步特性.如您所见,您将一个函数(回调或关闭)传递给 hget .Redis客户端从服务器检索到结果后,就会立即调用此函数.如果发生错误,则第一个参数将是错误对象,否则,第一个参数将为null.第二个参数将保存结果.

Also make sure you understand the concept of callbacks and closures in JavaScript as well as the asynchronous nature of node.js. As you can see, you pass a function (callback or closure) to hget. This function gets called as soon as the redis client has retrieved the result from the server. The first argument will be an error object if an error occurred, otherwise the first argument will be null. The second argument will hold the results.

这篇关于如何通过Node.js为Redis数据库发出HGET/GET命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 09:19