Created
October 15, 2019 03:59
-
-
Save Haleluak/2739135c115599a461e2a5bf9a1ba33a to your computer and use it in GitHub Desktop.
Handling 1 Million Requests per Minute with Go
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
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| ) | |
| type Dispatcher struct { | |
| // A pool of workers channels that are registered with the dispatcher | |
| maxWorkers int | |
| WorkerPool chan chan Job | |
| } | |
| func NewDispatcher(maxWorkers int) *Dispatcher { | |
| pool := make(chan chan Job, maxWorkers) | |
| return &Dispatcher{WorkerPool: pool, maxWorkers: maxWorkers} | |
| } | |
| func (d *Dispatcher) Run() { | |
| // starting n number of workers | |
| for i := 0; i < d.maxWorkers; i++ { | |
| worker := NewWorker(d.WorkerPool) | |
| worker.Start() | |
| } | |
| go d.dispatch() | |
| } | |
| func (d *Dispatcher) dispatch() { | |
| fmt.Println("Worker que dispatcher started...") | |
| for { | |
| select { | |
| case job := <-JobQueue: | |
| log.Printf("a dispatcher request received") | |
| // a job request has been received | |
| go func(job Job) { | |
| // try to obtain a worker job channel that is available. | |
| // this will block until a worker is idle | |
| jobChannel := <-d.WorkerPool | |
| // dispatch the job to the worker job channel | |
| jobChannel <- job | |
| }(job) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment