复制请求 程序正在处理 用户的HTTP请求, 或者检索一个数据块。你可以将请求分发到多个处理程序(无论是 goroutine ,进程, 还是服务器),其中一个将比其他 处理程序返回更快,可以 立即返回结果。 下面例子 在 单个进程中, 使用多个goroutine 作为处理程序。 goroutine 将随机休眠一段时间以模拟不同的负载,
func main() {
doWork := func(done <-chan interface{}, id int, wg *sync.WaitGroup, result chan <- int) {
started := time.Now()
defer wg.Done()
//模拟随机负载
simulatedLoadTime := time.Duration(1 + rand.Intn(5))*time.Second
select{
case <-done:
case <-time.After(simulatedLoadTime):
}
select{
case <-done:
case result <- id:
}
took := time.Since(started)
//显示处理程序需要多长时间
if took < simulatedLoadTime{
took = simulatedLoadTime
}
fmt.Printf("%v took %v\n", id, took)
}
done := make(chan interface{})
result := make(chan int)
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i<10; i++{
go doWork(done, i, &wg, result)
}
firstReturned := <- result
close(done)
wg.Wait()
fmt.Printf("Received an answer from #%v\n", firstReturned)
}
//6 took 1.002598933s
//0 took 1.002687636s
//9 took 2s
//2 took 5s
//3 took 1.002655195s
//4 took 3s
//5 took 2s
//1 took 3s
//8 took 4s
//7 took 2s
//Received an answer from #6
所有的处理程序 都应该是尽可能 等价的,有相同的机会处理请求。 建立和维护这样一套系统 有很大的代价, 但如果你追求的是响应速度, 那是一种非常有价值的架构。这种方式天然提供了容错 和 可扩展性。