-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathioredis_basics.js
83 lines (68 loc) · 2.21 KB
/
ioredis_basics.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const Redis = require('ioredis');
// Basic connection, will use defaults if object not provided.
const redis = new Redis({
port: 6379,
host: '127.0.0.1',
// password: 'sssssh',
});
const ioRedisBasics = async () => {
// First example.
redis.hincrby('mykey', 'myfield', 5, function (err, results) {
console.log(results);
});
const results = await redis.hincrby('mykey', 'myfield', 5);
console.log(results);
// Basic Redis commands.
const PLANET_LIST_KEY = 'planets';
const planets = [
'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter',
'Saturn', 'Uranus', 'Neptune', 'Pluto'
];
await redis.del(PLANET_LIST_KEY);
const listLength = await redis.lpush(PLANET_LIST_KEY, planets);
console.log(`LPUSH, planets list length is ${listLength}.`);
// LRANGE returns an array of strings.
const somePlanets = await redis.lrange(PLANET_LIST_KEY, 0, 4);
console.log('LRANGE, retrieved:');
console.log(somePlanets);
// Pipelining with chained commands. Transactions
// work in the same manner.
await redis.pipeline()
.hset('planet:mercury', 'name', 'Mercury', 'diameter', 4879,
'diameterUnit', 'km')
.hset('planet:venus', 'name', 'Venus', 'diameter', 12104,
'diameterUnit', 'km')
.hset('planet:earth', 'name', 'Earth', 'diameter', 12756,
'diameterUnit', 'km')
.hset('planet:mars', 'name', 'Mars', 'diameter', 6779,
'diameterUnit', 'km')
.exec();
// HGETALL returns an object by default.
const planet = await redis.hgetall('planet:earth');
console.log('HGETALL planet:earth');
console.log(planet);
// Get results from a pipeline.
const pipeResults = await redis.pipeline()
.hgetall('planet:venus')
.hgetall('planet:earth')
.exec();
/*
pipeResults is an array of arrays, each containing any
error, and the response object from the hgetall command.
[
[ null, { name: 'Venus', diameter: '12104',
diameterUnit: 'km' } ],
[ null, { name: 'Earth', diameter: '12756',
diameterUnit: 'km' } ]
]
*/
console.log('Pipeline results:');
console.log(pipeResults);
// Disconnect
redis.quit();
};
try {
ioRedisBasics();
} catch (e) {
console.error(e);
}