Redis
安装依赖包
npm install -save redis
创建redis连接
const redis = require('redis');
const client = redis.createClient(6379, '127.0.0.1');
client.info(function(error, response){
console.log(error, response);
})
其中 createClient(port, host, options) 函数可接受三个参数,第一个参数是连接端口,第二个参数是主机IP/名称,第三个参数则是配置项,KEY=>VALUE形式,如:
const client = redis.createClient(63719, '127.0.0.1', {connect_timeout:1}); //增加超时选项(毫秒)
使用方法示例
SET
client.set(key, value, callback) callback函数有2个回调参数,error和response,error表示操作过程中的错误提示值为null表示没有错误,response为String类型
client.set('name', 'Nemo', function(error, response){
console.log(error, response); // will print: null 'OK'
});
若传入的对象是json,则需要进行转换,否则会出错
错误示例:
client.set('student', {name: 'Nemo', age: 22}, function(error, response){
console.log(error, response);
});
client.get('student', function(err,response){
console.log(err, response); //will print Nemo
});
结果:
Object
正确示例:
// 重写toString方法
Object.prototype.toString = function() {
return JSON.stringify(this);
}
client.set('student', {name: 'Nemo', age: 22}, function(error, response){
console.log(error, response);
});
client.get('student', function(err,response){
console.log(err, response); //will print Nemo
});
结果:
json
GET
client.get(key, callback) callback函数有2个回调参数,error和value,error表示操作过程中的错误提示值为null表示没有错误,value为获取的值:null表示未获取到当前key对应的值,redis中不存在,
client.get('name', function(err, value){
console.log(err, value); //will print: null 'Nemo'
})
消息中介
redis中支持订阅与发布
订阅方:
const redis = require('redis');
const client = redis.createClient(6379, '127.0.0.1');
client.subscribe('OneTest');
client.on('message', function(channel, msg){
console.log('client.on message, channel:', channel, ' message:', msg);
});
发布方:
const redis = require('redis');
const client = redis.createClient(6379, '127.0.0.1');
client.publish('OneTest', 'message form subscription');
先后启动订阅方、发布方:
订阅与发布
Promises
当你的Node环境为v8或以上版本,推荐使用promisify
来操作redis:
const redis = require('redis');
const { promisify } = require('util');
const client = redis.createClient(6379, '127.0.0.1');
const getAsync = promisify(client.get).bind(client);
// 使用方法①
return getAsync('student').then(function(res) {
console.log(res); // => '{"name":"Nemo","age":22}'
});
// 使用法法②
async function student() {
const res = await getAsync('student');
console.log(res); // => '{"name":"Nemo","age":22}'
};
student();
未完待续~~~
本文参考资源如下:
网友评论