luminyra
使用指南

超时与组合

用 Timeout 区分自身期限与调用方取消,并把重试、熔断和超时嵌套在一起。

限制调用时长

Timeout 是一个时长类型,用法是 resil.Timeout(2*time.Second).Get(ctx, op)。它给操作一个到期结束的 context。与直接使用 context.WithTimeout 的区别在于错误:自身期限到达时,错误匹配 ErrTimeout,同时仍匹配 context.DeadlineExceeded;调用方取消时,错误原样返回。

resil/example_test.go
slow := func(ctx context.Context) error {
	select {
	case <-time.After(time.Second):
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}
err := resil.Timeout(10*time.Millisecond).Do(context.Background(), slow)
fmt.Println(errors.Is(err, resil.ErrTimeout))
预期输出
true
在 GitHub 查看

Timeout 不会丢下仍在运行的操作,它只取消 context 并等待操作返回,因此不启动 goroutine,也不会泄漏。代价是不响应 context 的操作无法被打断。

嵌套三个构件

三者以闭包嵌套,顺序在调用处一目了然。通常的顺序是重试包熔断、熔断包超时:

  • 每次尝试都经过熔断器,并拥有独立的期限;
  • 超时的尝试会被重试,也会被熔断器计为失败;
  • 熔断器打开后返回 ErrOpen,重试默认不重试它,立即停止;
  • 调用方取消的请求既不重试,也不计入熔断统计。

示例中服务第一次卡住,第二次返回 502,第三次成功。

resil/examples/combined/main.go
breaker, err := resil.NewBreaker(resil.BreakerConfig{
	FailureRate: 0.5,              // open when half the calls fail...
	Window:      time.Minute,      // ...over the last minute...
	MinRequests: 20,               // ...once there are 20 of them
	Cooldown:    10 * time.Second, // then probe again after 10s
})
if err != nil {
	panic(err)
}
retry := resil.Retry{
	Attempts: 4,
	Delay:    20 * time.Millisecond,
	OnRetry: func(attempt int, err error, _ time.Duration) {
		fmt.Printf("attempt %d: %v (timeout: %v)\n", attempt, err, errors.Is(err, resil.ErrTimeout))
	},
}
timeout := resil.Timeout(100 * time.Millisecond)

quote, err := retry.Get(context.Background(), func(ctx context.Context) (Quote, error) {
	return breaker.Get(ctx, func(ctx context.Context) (Quote, error) {
		return timeout.Get(ctx, fetchQuote)
	})
})
fmt.Printf("quote=%+v err=%v breaker=%s\n", quote, err, breaker.State())
在 GitHub 查看

测试会等待的代码

resil 通过标准库的 time 包计时和等待,在 testing/synctest 的气泡中,重试的退避和熔断器的冷却会瞬间完成,测试无需真实等待。

本页目录