luminyra

快速上手

运行带退避和 Stop 的重试示例,再把重试、熔断和超时组合起来。

运行重试示例

使用 Go 1.27 或更高版本,安装 resil 后将完整示例保存到 main.go 并运行 go run .。在 resil 源码目录可直接执行 go run ./examples/retry。

go get github.com/luminyra/resil
完整重试示例
// Command retry calls a flaky service with exponential backoff, logs every
// retry, and gives up at once on an error that retrying cannot fix.
package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/luminyra/resil"
)

var errNotFound = errors.New("order not found")

// fetchOrder fails twice with a temporary error, then succeeds. It returns
// errNotFound, marked with resil.Stop, for unknown orders.
func fetchOrder(calls *int) func(ctx context.Context, id int) (string, error) {
	return func(ctx context.Context, id int) (string, error) {
		*calls++
		if id != 42 {
			return "", resil.Stop(errNotFound)
		}
		if *calls < 3 {
			return "", errors.New("503 service unavailable")
		}
		return "order 42: 3 items", nil
	}
}

func main() {
	ctx := context.Background()

	retry := resil.Retry{
		Attempts: 5,
		Delay:    50 * time.Millisecond,
		MaxDelay: time.Second,
		Jitter:   0.2,
		OnRetry: func(attempt int, err error, wait time.Duration) {
			fmt.Printf("attempt %d failed (%v), retrying in about %s\n", attempt, err, wait.Round(10*time.Millisecond))
		},
	}

	for _, id := range []int{42, 7} {
		calls := 0
		fetch := fetchOrder(&calls)
		order, err := retry.Get(ctx, func(ctx context.Context) (string, error) {
			return fetch(ctx, id)
		})
		fmt.Printf("order %d: %q, err=%v, calls=%d\n", id, order, err, calls)
	}
}
在 GitHub 查看

订单 42 前两次返回 503,第三次成功;订单 7 返回用 Stop 包装的“未找到”,只调用一次就停止。

观察重试过程

Retry 是普通结构体,字段都可省略。下方测试中,操作前两次失败,第三次成功,Retry.Do 返回 nil。

resil/example_test.go
attempt := 0
err := resil.Retry{Attempts: 4, Delay: time.Millisecond}.Do(context.Background(), func(context.Context) error {
	attempt++
	fmt.Println("attempt", attempt)
	if attempt < 3 {
		return errors.New("unavailable")
	}
	return nil
})
fmt.Println(err)
预期输出
attempt 1
attempt 2
attempt 3
<nil>
在 GitHub 查看

组合三个构件

按“重试包熔断、熔断包超时”的顺序嵌套:每次尝试都经过熔断器并拥有独立的期限,超时的尝试会被重试并计为失败,熔断器一旦打开,重试立即停止。

resil/example_test.go
breaker, err := resil.NewBreaker(resil.BreakerConfig{Failures: 3, Cooldown: 10 * time.Second})
if err != nil {
	panic(err)
}
retry := resil.Retry{Attempts: 3, Delay: time.Millisecond}

calls := 0
fetch := func(ctx context.Context) (string, error) {
	calls++
	if calls < 3 {
		return "", errors.New("connection reset")
	}
	return "alice", nil
}

name, err := retry.Get(context.Background(), func(ctx context.Context) (string, error) {
	return breaker.Get(ctx, func(ctx context.Context) (string, error) {
		return resil.Timeout(time.Second).Get(ctx, fetch)
	})
})
fmt.Println(name, err, calls)
预期输出
alice <nil> 3
在 GitHub 查看

接着阅读重试与退避,了解等待时间如何计算以及哪些错误不会被重试。

本页目录