原文ibm redis中文社区
安装
通过命令行添加 Node_Redis 插件
npm install redis
--save
使用
var redis
= require('redis');
var redis
= redis
.createClient({ "host": "127.0.0.1", "port": "6379" });
redis
.on('error', function (err
) { console
.log('error
event
- ' + redis.host + ':' + redis.port + ' - '
+ err
); });
redis
.get('key',function(res
) { console
.log(业务逻辑
) });
client
.set("string key", "string val", redis
.print
);
client
.hset("hash key", "hashtest 1", "some value", redis
.print
);
client
.hset(["hash key", "hashtest 2", "some other value"], redis
.print
);
client
.hkeys("hash key", function (err
, replies
) {
console
.log(replies
.length
+ " replies:");
replies
.forEach(function (reply
, i
) {
console
.log(" " + i
+ ": " + reply
);
});
client
.quit();
});
异步调用
function redis_get_string() { redis
.set('key',
['string'], function(err
, res
) { redis
.get('key', function(err
, res
) {
console
.log(res
);
同步调用
引入 JavaScript 异步模块 bluebird
npm install
--save bluebird
引入 bluebird 使 Node_Redis API 异步化
var bluebird
= require('bluebird');
var redis
= require('redis');
bluebird
.promisifyAll(redis
.RedisClient
.prototype
);
bluebird
.promisifyAll(redis
.Multi
.prototype
);
同步返回数据
async exist(search
){
let user
= await redis
.getAsync(search
);
}
异步 Promise 链式调用
function redis_setget_string_async() { var promise
=
redis
.setAsync('key', ['string']).then(function(res
) { return redis
.getAsync('key');
N
ative Promises If you are using node v8 or higher, you can promisify node_redis with util.promisify as in:
const {promisify
} = require('util');
const getAsync
= promisify(client
.get).bind(client
);
now getAsync is a promisified version of client.get:
return getAsync('foo').then(function(res
) {
console
.log(res
);
});
or using async await:
async myFunc() {
const res
= await getAsync('foo');
console
.log(res
);
}