Created
June 15, 2022 21:00
-
-
Save ragokan/82f2a99363a730226d08340bb3a2a2f5 to your computer and use it in GitHub Desktop.
Redis Nest Client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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