← 中文资源

简体中文版本

对冲请求:先到先得

同时向多个副本发起请求,用 select 取最先返回的响应,胜者确定后 cancel 派生 context 收掉慢的 goroutine,通道带缓冲保证不泄漏。

阅读英文原文

实现说明

对冲请求:先到先得可以归结为函数 replica、main。 goroutine 干活,channel 把结果送回来——两个上下文不直接共享内存。清理逻辑用 defer 挂载,函数的任何退出路径都会执行。

使用要点

  • 跑完文件,输出里会留下标记——winner:、loser drained via context。
  • main 按顺序串起 replica;运行文件就会把这个流程跑一遍。

常见问题

运行「对冲请求:先到先得」会打印什么?

运行文件本身,winner:、loser drained via context 这些前缀各对应一段演示逻辑。

主签名形如 func replica(ctx context.Context, name string, delay time.Duration) <-chan string

核心语句

func replica(ctx context.Context, name string, delay time.Duration) <-chan string {
	ch := make(chan string, 1)
	go func() {
		select {
		case <-time.After(delay):
			ch <- name + " answered"
		case <-ctx.Done():
		}
	}()
	return ch
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

代码示例

package main

import (
	"context"
	"fmt"
	"time"
)

// 对冲请求:向多个副本同时发起,返回带缓冲的结果通道
func replica(ctx context.Context, name string, delay time.Duration) <-chan string {
	ch := make(chan string, 1)
	go func() {
		select {
		case <-time.After(delay):
			ch <- name + " answered"
		case <-ctx.Done():
		}
	}()
	return ch
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	first := replica(ctx, "replica-a", 30*time.Millisecond)
	second := replica(ctx, "replica-b", 80*time.Millisecond)

	// first-wins:谁先到用谁,慢副本不再等待
	select {
	case res := <-first:
		fmt.Println("winner:", res)
	case res := <-second:
		fmt.Println("winner:", res)
	}

	// 胜者已定:cancel 让慢 goroutine 从 ctx.Done 退出;缓冲为 1
	// 即使它已完成发送也不会阻塞泄漏
	cancel()
	time.Sleep(10 * time.Millisecond)
	fmt.Println("loser drained via context")
}