You need separate clients in Redis to publish and subscribe:
import "dotenv/config";
import express from "express";
import { createClient } from "redis";
const app = express();
const REDIS_URL = process.env.REDIS_URL ?? "redis://localhost:6379";
const PORT = Number(process.env.PORT ?? 3000);
const publisher = createClient({ url: REDIS_URL });
const subscriber = createClient({ url: REDIS_URL });
await publisher.connect();
await subscriber.connect();
console.log("Connected to Redis");
// Subscriber — lauscht auf dem "jobs"-Channel und verarbeitet Jobs
await subscriber.subscribe("jobs", (message) => {
const job = JSON.parse(message);
console.log(`[Worker] Starte Job ${job.id}: ${job.type}`);
// Hier wuerde die eigentliche Arbeit passieren...
console.log(`[Worker] Job ${job.id} abgeschlossen`);
});
// Publisher — GET-Request stuert einen Job ein
app.get("/job", async (req, res) => {
console.log("job endpoint");
const id = crypto.randomUUID();
const job = { id, type: "email", createdAt: new Date().toISOString() };
await publisher.publish("jobs", JSON.stringify(job));
res.json({ status: "queued", job });
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});