在Go語言中,實現(xiàn)并發(fā)編程的負載均衡可以通過以下幾種方式:
package main
import (
"fmt"
"sync"
)
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Printf("Worker %d started job %d\n", id, j)
// 模擬任務處理時間
time.Sleep(time.Second)
fmt.Printf("Worker %d finished job %d\n", id, j)
results <- j * 2
}
}
func main() {
const numJobs = 10
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
// 創(chuàng)建3個Goroutines來處理任務
var wg sync.WaitGroup
for w := 1; w <= 3; w++ {
wg.Add(1)
go worker(w, jobs, results)
}
// 分發(fā)任務
for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs)
// 收集結果
go func() {
wg.Wait()
close(results)
}()
for r := range results {
fmt.Println("Result:", r)
}
}
package main
import (
"fmt"
"sync"
)
const numWorkers = 3
const maxJobs = 10
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for j := range jobs {
fmt.Printf("Worker %d started job %d\n", id, j)
// 模擬任務處理時間
time.Sleep(time.Second)
fmt.Printf("Worker %d finished job %d\n", id, j)
results <- j * 2
}
}
func main() {
jobs := make(chan int, maxJobs)
results := make(chan int, maxJobs)
// 創(chuàng)建工作池
var wg sync.WaitGroup
for w := 1; w <= numWorkers; w++ {
wg.Add(1)
go worker(w, jobs, results, &wg)
}
// 分發(fā)任務
for j := 1; j <= maxJobs; j++ {
jobs <- j
}
close(jobs)
// 等待所有工作完成
wg.Wait()
close(results)
// 收集結果
for r := range results {
fmt.Println("Result:", r)
}
}
github.com/uber-go/ratelimit
可以用來限制并發(fā)任務的速率,從而實現(xiàn)負載均衡。這些方法可以根據(jù)具體的應用場景和需求進行選擇和組合,以實現(xiàn)高效的并發(fā)編程負載均衡。