安装
通过命令行添加 Node_Redis 插件
npm install redis --save
使用
// 创建一个 Redis 客户端并连接到 Redis-Server
var redis = require('redis');
var redis = redis.createClient({ "host": "127.0.0.1", "port": "6379" });
//注册 Redis 错误事件监听
redis.on('error', function (err) { console.log('error
event - ' + redis.host + ':' + redis.port + ' - ' + err); });
//基本使用
redis.get('key',function(res) { console.log(业务逻辑) }); //查询key的值
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); //打印'string' }); }); };
同步调用
- 引入 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');
//返回 Promise }).then(function(res) { console.log(res); //打印'string' Q.resolve(res);
//返回 Promise }); return promise; }
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:
// We expect a value 'foo': 'bar' to be present
// So instead of writing client.get('foo', cb); you have to write:
return getAsync('foo').then(function(res) {
console.log(res); // => 'bar'
});
or using async await:
async myFunc() {
const res = await getAsync('foo');
console.log(res);
}