Skip to content
เข้าสู่ระบบ

Message Queues

Message queues ช่วยให้ระบบ communicate แบบ asynchronous

package main
import (
"fmt"
"sync"
"time"
)
type Job struct {
ID int
Payload string
}
type Queue struct {
jobs chan Job
wg sync.WaitGroup
}
func NewQueue(size int) *Queue {
return &Queue{
jobs: make(chan Job, size),
}
}
func (q *Queue) Push(job Job) {
q.jobs <- job
}
func (q *Queue) StartWorkers(num int, handler func(Job)) {
for i := 0; i < num; i++ {
q.wg.Add(1)
go func(workerID int) {
defer q.wg.Done()
for job := range q.jobs {
fmt.Printf("Worker %d processing job %d\n", workerID, job.ID)
handler(job)
}
}(i)
}
}
func (q *Queue) Close() {
close(q.jobs)
q.wg.Wait()
}
func main() {
queue := NewQueue(100)
// Start workers
queue.StartWorkers(3, func(job Job) {
time.Sleep(100 * time.Millisecond)
fmt.Printf("Completed job %d: %s\n", job.ID, job.Payload)
})
// Push jobs
for i := 1; i <= 10; i++ {
queue.Push(Job{ID: i, Payload: fmt.Sprintf("Task %d", i)})
}
// Wait for completion
queue.Close()
fmt.Println("All jobs completed!")
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด