在Go语言中,实现并发编程的负载均衡可以通过以下几种方式:
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)
// 创建3个Goroutines来处理任务
var wg sync.WaitGroup
for w := 1; w <= 3; w++ {
wg.Add(1)
go worker(w, jobs, results)
}
// 分发任务
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)
// 创建工作池
var wg sync.WaitGroup
for w := 1; w <= numWorkers; w++ {
wg.Add(1)
go worker(w, jobs, results, &wg)
}
// 分发任务
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
可以用来限制并发任务的速率,从而实现负载均衡。这些方法可以根据具体的应用场景和需求进行选择和组合,以实现高效的并发编程负载均衡。