NoSQL数据库(三)04-Redis进阶与实战——nodejs操作redis数据库之ioredis更新属于node_redis改良版 & ioredis的可视化工具安装、基本语法、管道与事务
nodejs操作redis数据库
框架选择
- node_redis
- ioredis
node_redis星星更多但是我们选择ioredis,因为ioredis更新,属于node_redis改良版。
【文章】ioredis 的开发背景以及与 node_redis 合并的计划
不过ioredis与node_redis的作者正在讨论将两者合为一个库。
- ioredis安装
npm install ioredis
可视化工具安装
- 收费
- 免费:AnotherRedisDesktopManager
安装
https://github.com/mood6666/AnotherRedisDesktopManager
基本语法
- 一些简单的操作
var Redis = require('ioredis');
var redis = new Redis();
redis.set('foo', 'bar');
redis.get('foo', function (err, result) {
console.log(result);
});
redis.del('foo');
// Or using a promise if the last argument isn't a function
redis.get('foo').then(function (result) {
console.log(result);
});
// Arguments to commands are flattened,so the following are the same:
redis.sadd('set', 1, 3, 5, 7);
redis.sadd('set', [1, 7]);
// All arguments are passed directly to the redis server:
redis.set('key', 100, 'EX', 10);
- 连接redis
new Redis() // Connect to 127.0.0.1:6379
new Redis(6380) // 127.0.0.1:6380
new Redis(6379, '192.168.1.1') // 192.168.1.1:6379
new Redis('/tmp/redis.sock')
new Redis({
port: 6379, // Redis port
host: '127.0.0.1', // Redis host
family: 4, // 4 (IPv4) or 6 (IPv6)
password: 'auth',
db: 0
})
- pipelining
对redis实现的管道,避免出现前面提到的往返时延问题。
var pipeline = redis.pipeline();
pipeline.set('foo', 'bar');
pipeline.del('cc');
pipeline.exec(function (err, results) {
// `err` is always null,and `results` is an array of responses
// corresponding to the sequence of queued commands.
// Each response follows the format `[err,result]`.
});
// You can even chain the commands:
redis.pipeline().set('foo', 'bar').del('cc').exec(function (err, results) {
});
// `exec` also returns a Promise:
var promise = redis.pipeline().set('foo', 'bar').get('foo').exec();
promise.then(function (result) {
// result === [[null,'OK'],[null,'bar']]
});
还有另外一种调用方式:
redis.pipeline([
['set', 'foo', 'bar'],
['get', 'foo']
]).exec(function () { /* ... */ });
- 事务
redis.multi().set('foo', 'bar').get('foo').exec(function (err, results) {
// results === [[null,'bar']]
});
实例
node_index.js
var Redis = require('ioredis');
var redis = new Redis(); // 实例化了一个客户端
// redis.set('foo','bar');
// redis.get('foo',function(err,result) { // 第一个参数是err这是nodejs的约定
// console.log('result',result)
// })
// // redis.del('foo');
// // redis.sadd('set',1,3,5,7);
// redis.sadd('set',[2,4,6,8]); // 类似apply和call
// // 需要过期时间
// redis.set('guoqi',100,'EX',5);
// var pipeline = redis.pipeline();
// pipeline.set('hello','world').set('nihao','china').exec();
redis.multi().set('shiwu3', 'aaa').set('shiwu4', asdsad).exec();
原文地址:https://blog.csdn.net/weixin_44867717/article/details/131692990
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。