nodejs redis

原文ibm
redis中文社区

安装

通过命令行添加 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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值