feign.net 使用consul服务发现 配置
所有依赖
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> <InvariantGlobalization>true</InvariantGlobalization> </PropertyGroup> <ItemGroup> <PackageReference Include="Feign" Version="1.5.2" /> <PackageReference Include="Feign.DependencyInjection" Version="1.5.2" /> <PackageReference Include="Feign.Steeltoe" Version="1.5.1" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.3" /> <PackageReference Include="Serilog" Version="3.1.1" /> <PackageReference Include="Serilog.Sinks.Console" Version="5.0.0" /> <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" /> <PackageReference Include="Steeltoe.Discovery.Consul" Version="3.2.5" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" /> </ItemGroup> </Project>
appsettings.json
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "consul": { "host": "127.0.0.1", "port": 8500, "token":"ca6a320c-f654-5d82-bba7-3df712aee755", "discovery": { "enabled": false, "register": false, "port": "5188", "ipAddress": "127.0.0.1", "preferIpAddress": true } }, "AllowedHosts": "*" }
// Program.cs
using Feign;
using Microsoft.AspNetCore.Mvc;
using Project;
using Steeltoe.Discovery.Client;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// 使用包 Steeltoe.Discovery.Consul 3.2.5
builder.Services.AddDiscoveryClient(builder.Configuration);
builder.Services.AddFeignClients(
options =>
{
// 记录日志
options.FeignClientPipeline.UseReceivedResponse(context =>
{
Console.WriteLine("请求的url:"+context.Request.BaseUrl);
//响应数据后触发
return new ValueTask(Task.CompletedTask);
});
}
).AddSteeltoe();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
// app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapGet("/paytest", async ( [FromServices] ITestService testService ) =>
{
// 非常好,终于实现
var res = await testService.GetByIdAsync();
return res;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.Run();
ITestService
using Feign; namespace Project; [FeignClient("weightService")] [NonFeignClient] public interface ITestParentService<TModel> { /// <summary> /// async get /// </summary> /// <returns></returns> [RequestMapping("", Method = "GET")] [MethodId("GetAsync")] Task<TModel> GetByIdAsync(); } [RequestMapping("")] public interface ITestService:ITestParentService<string> { }