-
-
Save laocoi/5c9a7f0948dfa6e9a30d57c246f4d114 to your computer and use it in GitHub Desktop.
Cloudflare worker - Example for Queue scaling
This file contains 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
//https://www.npmjs.com/package/round-robin-js | |
import { RandomRoundRobin } from 'round-robin-js'; | |
async function sender(queue: string, message: any, env: Env) { | |
try { | |
const processors = { | |
PROCESSOR1: env.ENVIRONMENT === 'dev' ? env.PROCESSOR1_DEV : env.PROCESSOR1, | |
PROCESSOR2: env.ENVIRONMENT === 'dev' ? env.PROCESSOR2_DEV : env.PROCESSOR2, | |
PROCESSOR3: env.ENVIRONMENT === 'dev' ? env.PROCESSOR3_DEV : env.PROCESSOR3, | |
PROCESSOR4: env.ENVIRONMENT === 'dev' ? env.PROCESSOR4_DEV : env.PROCESSOR4, | |
}; | |
const processor = processors[queue]; | |
if (processor) { | |
await processor.send(message); | |
message.ack(); | |
} | |
} catch (error) { | |
console.log(error); | |
throw error; | |
} | |
} | |
async function response(request: Request, env: Env, writeKey: string) { | |
const data = (await request.json()) as Data; | |
const queues = new RandomRoundRobin<string>(['PROCESSOR1', 'PROCESSOR2', 'PROCESSOR3', 'PROCESSOR4']); | |
const queue = queues.next().value; | |
const message = { | |
data | |
}; | |
await sender(queue, message, env); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment