Yzl.Extensions.Http.OpenFeign 0.1.12

There is a newer version of this package available.
See the version list below for details.
dotnet add package Yzl.Extensions.Http.OpenFeign --version 0.1.12
                    
NuGet\Install-Package Yzl.Extensions.Http.OpenFeign -Version 0.1.12
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Yzl.Extensions.Http.OpenFeign" Version="0.1.12" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Yzl.Extensions.Http.OpenFeign" Version="0.1.12" />
                    
Directory.Packages.props
<PackageReference Include="Yzl.Extensions.Http.OpenFeign" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Yzl.Extensions.Http.OpenFeign --version 0.1.12
                    
#r "nuget: Yzl.Extensions.Http.OpenFeign, 0.1.12"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Yzl.Extensions.Http.OpenFeign@0.1.12
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Yzl.Extensions.Http.OpenFeign&version=0.1.12
                    
Install as a Cake Addin
#tool nuget:?package=Yzl.Extensions.Http.OpenFeign&version=0.1.12
                    
Install as a Cake Tool

Yzl.Extensions.Http.OpenFeign 总体架构设计

设计目标

Yzl.Extensions.Http.OpenFeign 是一个 面向 .NET 8 的声明式 HTTP 客户端基础设施组件,主要目标:

  • 模拟 Java 世界的 OpenFeign,实现声明式 HTTP API 调用
  • 提供 接口自动代理、请求重试、熔断机制
  • 支持 Fallback 回退、请求超时与缓存
  • 提升业务开发效率,减少重复 HTTP 调用代码

等价于 Java 世界里的:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

配置示例

  1. 在Program.cs 中启用OpenFeign支持
using Yzl.Extensions.Common.Extensions;
using Yzl.Extensions.Http.OpenFeign;
using Test.Models;
using Test.Yzl.Extensions.Http.OpenFeign.Acs;
using Yzl.Extensions.Http.OpenFeign.Serializer;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// ===== Yzl.Extensions.Http.OpenFeign (启用OpenFeign客户端支持) =====
builder.Services.AddFeignStarter(builder.Configuration, options => { options.SerializerType = typeof(SystemTextJsonFeignSerializer); });

var app = builder.Build();

app.MapGet("/", () => "Hello .NET 8 + OpenFeign!");

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapGet("/feign-api-test", async (ITestApiFeignClient client) => new
{
    ping = await client.Ping(),
    user = await client.GetById(1),
    query = await client.Query(1, "Tom"),
    map = await client.QueryMap(new Dictionary<string, string> {{"age", "18"}, {"city", "bj"}}),
    create = await client.Create(new CreateUserRequest("Jerry", 20)),
    update = await client.Update(1, new UpdateUserRequest("Bob", 30)),
    header = await client.Headers("token-123"),
    delete = await client.Delete(1),
    timeout = client.TimeOut()
});

app.RegisterApplicationLifetimeEvents();

app.Run();
  1. 配置文件
{
  "spring": {
    "feign": {
      "default": {
        "timeout": 3000,
        "retry": {
          "enabled": true,
          "maxAttempts": 2,
          "delayMs": 200
        },
        "hedging": {
          "enabled": false,
          "maxAttempts": 1,
          "delayMs": 150
        },
        "circuitBreaker": {
          "enabled": true,
          "failureRatio": 0.2,
          "samplingSeconds": 30,
          "minimumThroughput": 5,
          "breakSeconds": 20
        }
      },
      "httpClient": {
        "keepAlive": {
          "enabled": true,
          "pingDelay": "00:00:30",
          "pingTimeout": "00:00:10"
        },
        "pool": {
          "idleTimeout": "00:05:00",
          "connectionLifetime": "00:10:00"
        }
      }
    }
  },
  "apis": {
    "internal-api-dev": "http://localhost:16062/",
    "internal-api": "http://xx:16021/internal-api-v4/"
  },
  "DetailedErrors": true,
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}
  1. 启用全局请求头
  • 自定义类实现IFeignRequestHeaderProvider接口
using Yzl.Extensions.Http.OpenFeign.Headers;

namespace Test.Yzl.Extensions.Http.OpenFeign.FeignImpl;

public class AuthHeaderProvider : IFeignRequestHeaderProvider
{
    public int Order => -100;

    public void Apply(IDictionary<string, string> headers)
    {
        headers["Authorization"] = "Bearer " + GetToken();
        headers.TryAdd("source", "PC111");
    }

    private string GetToken() => "xxx.yyy.zzz";
}

字段说明:

{
  "spring": {
    "feign": {

      // =========================
      // 默认 Feign 客户端配置
      // 对所有 FeignClient 生效
      // =========================
      "default": {

        // -------------------------
        // 请求超时时间(毫秒)
        // 等价于:
        // - HttpClient Timeout
        // - Polly TimeoutStrategy
        // -------------------------
        "timeout": 3000,

        // -------------------------
        // 重试策略配置
        // 仅对满足 ShouldHandle 条件的请求生效
        // 通常只建议用于 GET / 幂等请求
        // -------------------------
        "retry": {

          // 是否启用重试
          "enabled": true,

          // 最大重试次数(不含首次请求)
          // total attempts = 1 + max-attempts
          "maxAttempts": 2,

          // 每次重试的初始延迟(毫秒)
          // 实际延迟可能受指数退避影响
          "delayMs": 200
        },

        // -------------------------
        // 对冲(Hedging)策略
        // 并行发送备用请求以降低尾延迟
        // ⚠️ 高并发下慎用
        // -------------------------
        "hedging": {

          // 是否启用对冲请求
          "enabled": false,

          // 最大对冲请求次数
          // 1 = 不对冲
          "maxAttempts": 1,

          // 对冲请求触发延迟(毫秒)
          "delayMs": 150
        },

        // -------------------------
        // 熔断器(Circuit Breaker)配置
        // 用于防止级联失败
        // -------------------------
        "circuitBreaker": {

          // 是否启用熔断
          "enabled": true,

          // 失败比例阈值
          // 例如 0.2 表示 20% 请求失败即触发熔断
          "failureRatio": 0.2,

          // 统计窗口时间(秒)
          // 在该时间窗口内统计失败比例
          "samplingSeconds": 30,

          // 触发熔断所需的最小请求数
          // 防止低流量时误判
          "minimumThroughput": 5,

          // 熔断打开后的持续时间(秒)
          // 超过后进入 Half-Open 状态
          "breakSeconds": 20
        }
      }
    }
  }
}

  1. 使用示例
using Yzl.Extensions.Http.OpenFeign.Attributes;
using Yzl.Extensions.Http.OpenFeign.Attributes.Methods;
using Test.Models;
using Test.Yzl.Extensions.Http.OpenFeign.Acs.FallbackHandler;

namespace Test.Yzl.Extensions.Http.OpenFeign.Acs;

// url 区分环境配置时,可以使用 "{apis:internal-api}",apis:internal-api需要在配置文件中真实存在
[FeignClient(name: "test", url: "http://localhost:17007", fallback: typeof(TestApiFeignClientFallback))]
public interface ITestApiFeignClient
{
    [Get("/api/test/ping")]
    Task<string> Ping();

    [Get("/api/test/users/{id}")]
    Task<UserDto> GetById([PathVariable("id")] long id);

    [Get("/api/test/users/query")]
    Task<object> Query(
        [RequestParam("id")] long id,
        [RequestParam("name")] string name);

    [Get("/api/test/users/map")]
    Task<object> QueryMap([
            QueryMap]
        Dictionary<string, string> map);

    [Post("/api/test/users")]
    Task<UserDto> Create([
            RequestBody]
        CreateUserRequest req);

    [Put("/api/test/users/{id}")]
    Task<UserDto> Update(
        [PathVariable("id")] long id,
        [RequestBody] UpdateUserRequest req);

    [Delete("/api/test/users/{id}")]
    Task<bool> Delete([
            PathVariable("id")]
        long id);

    [Get("/api/test/headers")]
    Task<object> Headers([
            RequestHeader("X-Token")]
        string token);

    [Head("/api/test/head")]
    Task Head();

    [Get("/api/test/timeout")]
    string TimeOut();
}

using Yzl.Extensions.Common.Ioc.Attributes;
using Test.Models;

namespace Test.Yzl.Extensions.Http.OpenFeign.Acs.FallbackHandler;

public class TestApiFeignClientFallback : ITestApiFeignClient
{
    public Task<string> Ping()
    {
        throw new NotImplementedException();
    }

    public Task<UserDto> GetById(long id)
    {
        throw new NotImplementedException();
    }

    public Task<object> Query(long id, string name)
    {
        throw new NotImplementedException();
    }

    public Task<object> QueryMap(Dictionary<string, string> map)
    {
        throw new NotImplementedException();
    }

    public Task<UserDto> Create(CreateUserRequest req)
    {
        throw new NotImplementedException();
    }

    public Task<UserDto> Update(long id, UpdateUserRequest req)
    {
        throw new NotImplementedException();
    }

    public Task<bool> Delete(long id)
    {
        throw new NotImplementedException();
    }

    public Task<object> Headers(string token)
    {
        throw new NotImplementedException();
    }

    public Task Head()
    {
        throw new NotImplementedException();
    }

    public string TimeOut()
    {
        return "fallback timeout";
    }
}

如有使用问题或更好建议,请与作者联系。EMail:306337420@QQ.com。

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.21 114 10/13/2026
0.1.20 157 7/18/2026
0.1.19 129 7/4/2026
0.1.18 137 6/10/2026
0.1.17 136 6/3/2026
0.1.16 131 5/12/2026
0.1.15 129 5/3/2026
0.1.14 131 4/23/2026
0.1.13 138 4/20/2026
0.1.12 131 4/19/2026
0.1.11 138 4/16/2026
0.1.10 136 4/5/2026
0.1.9 135 3/31/2026
0.1.8 129 3/31/2026
0.1.7 132 3/31/2026
0.1.6 146 3/16/2026
0.1.5 142 3/2/2026
0.1.4 159 3/2/2026 0.1.4 is deprecated because it is no longer maintained and has critical bugs.
0.1.3 153 3/2/2026 0.1.3 is deprecated because it is no longer maintained and has critical bugs.
0.1.2 146 3/2/2026 0.1.2 is deprecated because it is no longer maintained and has critical bugs.
Loading failed