gRPC 客户端重试与截止时间实践Go 客户端(Service Config 重试与超时)import (
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
sc := `{"methodConfig":[{"name":[{"service":"api.ItemService"}],"retryPolicy":{"MaxAttempts":4,"InitialBackoff":"0.2s","MaxBackoff":"5s","BackoffMultiplier":2.0,"RetryableStatusCodes":["UNAVAILABLE","DEADLINE_EXCEEDED"]},"timeout":"3s"}]}`
conn, _ := grpc.Dial(
"127.0.0.1:7001",
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultServiceConfig(sc),
)
client := NewItemServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
resp, err := client.GetItem(ctx, &GetItemRequest{Id: "1"})
Java 客户端(截止时间)ManagedChannel ch = ManagedChannelBuilder.forTarget("127.0.0.1:7001").usePlaintext().build();
ItemServiceGrpc.ItemServiceBlockingStub stub = ItemServiceGrpc.newBlockingStub(ch);
Item resp = stub.withDeadlineAfter(3, java.util.concurrent.TimeUnit.SECONDS).getItem(GetItemRequest.newBuilder().setId("1").build());
要点Service Config 提供跨语言的重试/超时策略;请求级 `deadline/timeout` 控制单次调用总结结合重试与截止时间可提升客户端的健壮性并避免无限等待。

发表评论 取消回复