Skip to content

Instantly share code, notes, and snippets.

@ragokan
Created June 15, 2022 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ragokan/82f2a99363a730226d08340bb3a2a2f5 to your computer and use it in GitHub Desktop.
Save ragokan/82f2a99363a730226d08340bb3a2a2f5 to your computer and use it in GitHub Desktop.
Redis Nest Client
import Redis from "ioredis";
// Create pub and sub clients
const sub = new Redis();
const pub = new Redis();
// Set the queue names
const queue = "getHello";
const replyQueue = `${queue}.reply`;
// Subscribe to the queue
sub.subscribe(queue);
// Listen for messages
sub.on("message", async (channel, rawMessage) => {
if (channel !== queue) return;
// Parse the message
const message = JSON.parse(rawMessage) as IncomingMessage;
// Do something with the message and reply
for (let index = 0; index < 3; index++) {
const firstResponse: OutgoingMessage = {
id: message.id,
// Dispose if the message is the last one
isDisposed: index === 2,
response: `Hello ${message.data} - ${index}`,
};
// Publish the response
pub.publish(replyQueue, JSON.stringify(firstResponse));
}
});
interface IncomingMessage {
pattern: string;
data: string;
id: string;
}
interface OutgoingMessage {
response: string;
isDisposed: boolean;
id: string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment