-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredisClient.js
233 lines (207 loc) · 6.04 KB
/
redisClient.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/**
* @file redisClient.js
* @description Enhanced Redis client using RxJS and Pub/Sub that writes, reads, and outputs messages to/from a Redis database.
* @version 1.0.0
* @date 2023-10-05
* @license MIT
*
* @dependencies
* - redis: Redis client for Node.js
* - rxjs: Reactive Extensions for JavaScript
* - uuid: UUID generation for unique keys
*
* @usage
* To run the script, use the following command:
* ```
* node redisClient.js
* ```
*
* @notes
* - Ensure that Redis is running locally before running the script.
*
* @maintainer
* - GitHub Copilot
*/
const redis = require('redis');
const { Observable } = require('rxjs');
const { v4: uuidv4 } = require('uuid');
// Redis connection options
const redisOptions = {
url: 'redis://localhost:6379',
};
// Sample record template
const sampleRecordTemplate = {
name: 'John Doe',
email: 'john.doe@example.com',
age: 30,
createdAt: new Date().toISOString(),
};
function generateUniqueRecords(count) {
const records = [];
for (let i = 0; i < count; i++) {
const record = { ...sampleRecordTemplate, uuid: uuidv4() };
records.push(record);
}
return records;
}
function writeRecords() {
return new Observable((observer) => {
const client = redis.createClient(redisOptions);
const records = generateUniqueRecords(10);
client.on('error', (err) => console.error('Redis Client Error', err));
client.connect()
.then(() => {
console.log('Connected to Redis');
const promises = records.map((record) => {
const key = `user:${record.uuid}`;
return client.set(key, JSON.stringify(record));
});
return Promise.all(promises);
})
.then(() => {
console.log('Records inserted');
observer.next('Records inserted');
observer.complete();
})
.catch((error) => {
observer.error(error);
});
// Graceful shutdown
const shutdown = async () => {
if (client.isOpen) {
console.log('Disconnecting Redis client...');
await client.disconnect();
console.log('Redis client disconnected');
}
readRecords().subscribe({
next: (msg) => console.log(msg),
complete: () => {
console.log('Record reading complete');
process.exit(0);
},
error: (err) => console.error('Error reading records:', err),
});
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
return () => {
if (client.isOpen) {
client.disconnect().then(() => {
console.log('Redis connection closed');
});
}
};
});
}
function readRecords() {
return new Observable((observer) => {
const client = redis.createClient(redisOptions);
client.on('error', (err) => console.error('Redis Client Error', err));
client.connect()
.then(() => {
console.log('Connected to Redis');
return client.keys('user:*');
})
.then((keys) => {
const promises = keys.map((key) => client.get(key));
return Promise.all(promises);
})
.then((records) => {
records.forEach((record) => {
console.log('Record:', JSON.parse(record));
});
observer.next('Records read');
observer.complete();
})
.catch((error) => {
observer.error(error);
})
.finally(() => {
if (client.isOpen) {
client.disconnect().then(() => {
console.log('Redis connection closed');
});
}
});
// Graceful shutdown
const shutdown = async () => {
if (client.isOpen) {
console.log('Disconnecting Redis client...');
await client.disconnect();
console.log('Redis client disconnected');
}
process.exit(0);
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
return () => {
if (client.isOpen) {
client.disconnect().then(() => {
console.log('Redis connection closed');
});
}
};
});
}
function subscribeToChannel(channel) {
return new Observable((observer) => {
const subscriber = redis.createClient(redisOptions);
subscriber.on('error', (err) => console.error('Redis Subscriber Error', err));
subscriber.connect()
.then(() => {
console.log(`Subscribed to channel: ${channel}`);
subscriber.subscribe(channel, (message) => {
console.log(`Received message from channel ${channel}: ${message}`);
observer.next(message);
});
})
.catch((error) => {
observer.error(error);
});
// Graceful shutdown
const shutdown = async () => {
if (subscriber.isOpen) {
console.log('Disconnecting subscriber...');
await subscriber.unsubscribe(channel);
await subscriber.disconnect();
console.log('Subscriber disconnected');
}
process.exit(0);
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
return () => {
if (subscriber.isOpen) {
subscriber.unsubscribe(channel).then(() => {
subscriber.disconnect().then(() => {
console.log('Subscriber disconnected');
});
});
}
};
});
}
// Run the writeRecords and subscribeToChannel functions
writeRecords().subscribe({
next: (msg) => console.log(msg),
complete: () => console.log('Record writing complete'),
error: (err) => console.error('Error writing records:', err),
});
subscribeToChannel('test-channel').subscribe({
next: (msg) => console.log('Received message:', msg),
complete: () => console.log('Subscription complete'),
error: (err) => console.error('Error subscribing to channel:', err),
});
// Handle SIGINT and SIGTERM to read records
const handleShutdown = () => {
readRecords().subscribe({
next: (msg) => console.log(msg),
complete: () => {
console.log('Record reading complete');
process.exit(0);
},
error: (err) => console.error('Error reading records:', err),
});
};
process.on('SIGINT', handleShutdown);
process.on('SIGTERM', handleShutdown);