网关和服务发现

This commit is contained in:
hello 2024-04-20 14:33:06 +08:00
parent cea1278b71
commit 6f4a338bb4
14 changed files with 190 additions and 52 deletions

View File

@ -8,4 +8,8 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\HelloShop.ServiceDefaults\HelloShop.ServiceDefaults.csproj" /> <ProjectReference Include="..\HelloShop.ServiceDefaults\HelloShop.ServiceDefaults.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery.Yarp" Version="9.0.0-preview.3.24210.17" />
<PackageReference Include="Yarp.ReverseProxy" Version="2.1.0" />
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,9 @@
namespace HelloShop.ApiService.Infrastructure
{
public class ConfiguredServiceEndPoint
{
public required string ServiceName { get; set; }
public IReadOnlyCollection<string>? Endpoints { get; set; }
}
}

View File

@ -0,0 +1,35 @@

using Microsoft.Extensions.Options;
using Microsoft.Extensions.ServiceDiscovery.Abstractions;
namespace HelloShop.ApiService.Infrastructure;
public class ConfiguredServiceEndPointResolver(IConfiguration configuration, IOptions<ConfigurationServiceEndPointResolverOptions> resolverOptions) : IConfiguredServiceEndPointResolver
{
private readonly Lazy<IReadOnlyCollection<ConfiguredServiceEndPoint>> _serviceEndPoints = new(() =>
{
ArgumentException.ThrowIfNullOrWhiteSpace(resolverOptions.Value.SectionName, nameof(resolverOptions.Value.SectionName));
IConfigurationSection section = configuration.GetRequiredSection(resolverOptions.Value.SectionName);
List<ConfiguredServiceEndPoint> serviceEndPoints = [];
foreach (IConfigurationSection serviceSection in section.GetChildren())
{
string serviceName = serviceSection.Key;
serviceEndPoints.Add(new ConfiguredServiceEndPoint
{
ServiceName = serviceName,
Endpoints = serviceSection.GetChildren().SelectMany(x => x.Get<List<string>>() ?? []).Distinct().ToList()
});
}
return serviceEndPoints;
});
public async Task<IReadOnlyCollection<ConfiguredServiceEndPoint>> GetConfiguredServiceEndpointsAsync(CancellationToken cancellationToken = default)
{
return await Task.FromResult(_serviceEndPoints.Value);
}
}

View File

@ -0,0 +1,61 @@
using Yarp.ReverseProxy.Configuration;
using Yarp.ReverseProxy.LoadBalancing;
namespace HelloShop.ApiService.Infrastructure;
public class CustomReverseProxyConfigProvider(IConfiguredServiceEndPointResolver configuredServiceEndPointResolver) : IReverseProxyConfigProvider
{
public async Task<IReadOnlyList<RouteConfig>> GetRoutesAsync()
{
List<RouteConfig> routeConfigs = [];
foreach (var serviceEndPoint in await configuredServiceEndPointResolver.GetConfiguredServiceEndpointsAsync())
{
string serviceName = serviceEndPoint.ServiceName;
routeConfigs.Add(new RouteConfig()
{
// Forces a new route id each time GetRoutes is called.
RouteId = serviceName,
ClusterId = serviceName,
Match = new RouteMatch
{
// This catch-all pattern matches all request paths.
Path = $"{serviceEndPoint.ServiceName}/{{**remainder}}"
},
Transforms = [new Dictionary<string, string> { { "PathPattern", "{**remainder}" } }]
});
}
return routeConfigs;
}
public async Task<IReadOnlyList<ClusterConfig>> GetClustersAsync()
{
List<ClusterConfig> clusterConfigs = [];
foreach (var serviceEndPoint in await configuredServiceEndPointResolver.GetConfiguredServiceEndpointsAsync())
{
string serviceName = serviceEndPoint.ServiceName;
string? address = serviceEndPoint.Endpoints?.OrderBy(x => x)?.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(address))
{
UriBuilder uriBuilder = new(address) { Host = serviceName };
clusterConfigs.Add(new ClusterConfig()
{
ClusterId = serviceName,
LoadBalancingPolicy = LoadBalancingPolicies.FirstAlphabetical,
Destinations = new Dictionary<string, DestinationConfig>(StringComparer.OrdinalIgnoreCase)
{
{ "destination1", new DestinationConfig() { Address = uriBuilder.ToString() } }
},
});
}
}
return clusterConfigs;
}
}

View File

@ -0,0 +1,6 @@
namespace HelloShop.ApiService.Infrastructure;
public interface IConfiguredServiceEndPointResolver
{
public Task<IReadOnlyCollection<ConfiguredServiceEndPoint>> GetConfiguredServiceEndpointsAsync(CancellationToken cancellationToken = default);
}

View File

@ -0,0 +1,10 @@
using Yarp.ReverseProxy.Configuration;
namespace HelloShop.ApiService.Infrastructure;
public interface IReverseProxyConfigProvider
{
Task<IReadOnlyList<RouteConfig>> GetRoutesAsync();
Task<IReadOnlyList<ClusterConfig>> GetClustersAsync();
}

View File

@ -1,39 +1,37 @@
using HelloShop.ApiService.Infrastructure;
using Yarp.ReverseProxy.Configuration;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add service defaults & Aspire components. // Add service defaults & Aspire components.
builder.AddServiceDefaults(); builder.AddServiceDefaults();
// Add services to the container. // Add services to the container.
builder.Services.AddProblemDetails(); builder.Services.AddControllers().AddDataAnnotationsLocalization();
builder.Services.AddHttpForwarderWithServiceDiscovery();
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.LoadFromMemory(routes: [], clusters: []);
builder.Services.AddSingleton<IConfiguredServiceEndPointResolver, ConfiguredServiceEndPointResolver>();
builder.Services.AddSingleton<IReverseProxyConfigProvider, CustomReverseProxyConfigProvider>();
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseExceptionHandler();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
});
app.MapDefaultEndpoints(); app.MapDefaultEndpoints();
app.Run(); app.Services.GetRequiredService<IHostApplicationLifetime>().ApplicationStarted.Register(async () =>
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{ {
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); IReverseProxyConfigProvider provider = app.Services.GetRequiredService<IReverseProxyConfigProvider>();
} IReadOnlyList<RouteConfig> routes = await provider.GetRoutesAsync();
IReadOnlyList<ClusterConfig> clusters = await provider.GetClustersAsync();
app.Services.GetRequiredService<InMemoryConfigProvider>().Update(routes, clusters);
});
app.MapReverseProxy();
app.MapControllers();
app.Run();

View File

@ -5,7 +5,7 @@
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "weatherforecast", "launchUrl": "swagger",
"applicationUrl": "http://localhost:5391", "applicationUrl": "http://localhost:5391",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"

View File

@ -5,5 +5,29 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
} "ReverseProxy": {
"Routes": {
"testserviceRoute": {
"ClusterId": "testServiceCluster",
"Match": {
"Path": "testservice/{**remainder}"
},
"Transforms": [
{
"PathPattern": "{**remainder}"
}
]
}
},
"Clusters": {
"testServiceCluster": {
"Destinations": {
"testServiceCluster/destination1": {
"Address": "http://identityservice"
}
}
}
}
}
}

View File

@ -1,14 +1,18 @@
var builder = DistributedApplication.CreateBuilder(args); var builder = DistributedApplication.CreateBuilder(args);
var apiservice = builder.AddProject<Projects.HelloShop_ApiService>("apiservice"); var identityService = builder.AddProject<Projects.HelloShop_IdentityService>("identityservice");
builder.AddProject<Projects.HelloShop_IdentityService>("identityservice"); var orderingService=builder.AddProject<Projects.HelloShop_OrderingService>("orderingservice").WithReference(identityService);
builder.AddProject<Projects.HelloShop_OrderingService>("orderingservice"); var productService = builder.AddProject<Projects.HelloShop_ProductService>("productservice").WithReference(identityService);
builder.AddProject<Projects.HelloShop_ProductService>("productservice"); var basketService = builder.AddProject<Projects.HelloShop_BasketService>("basketservice").WithReference(identityService);
builder.AddProject<Projects.HelloShop_BasketService>("basketservice"); var apiservice = builder.AddProject<Projects.HelloShop_ApiService>("apiservice")
.WithReference(identityService)
.WithReference(orderingService)
.WithReference(productService)
.WithReference(basketService);
builder.AddProject<Projects.HelloShop_WebApp>("webapp").WithReference(apiservice); builder.AddProject<Projects.HelloShop_WebApp>("webapp").WithReference(apiservice);

View File

@ -22,10 +22,7 @@ builder.Services.AddCustomLocalization();
builder.Services.AddOpenApi(); builder.Services.AddOpenApi();
builder.Services.AddModelMapper().AddModelValidator(); builder.Services.AddModelMapper().AddModelValidator();
builder.Services.AddLocalization().AddPermissionDefinitions(); builder.Services.AddLocalization().AddPermissionDefinitions();
builder.Services.AddAuthorization().AddRemotePermissionChecker(options => builder.Services.AddAuthorization().AddRemotePermissionChecker().AddCustomAuthorization();
{
options.ApiEndpoint = "https://localhost:5001";
}).AddCustomAuthorization();
// End addd extensions services to the container. // End addd extensions services to the container.
var app = builder.Build(); var app = builder.Build();

View File

@ -9,10 +9,8 @@ using System.Net.Http.Json;
namespace HelloShop.ServiceDefaults.Authorization; namespace HelloShop.ServiceDefaults.Authorization;
public class RemotePermissionChecker(IHttpContextAccessor httpContextAccessor, IDistributedCache distributedCache, IHttpClientFactory httpClientFactory, IOptions<RemotePermissionCheckerOptions> options) : PermissionChecker(httpContextAccessor, distributedCache) public class RemotePermissionChecker(IHttpContextAccessor httpContextAccessor, IDistributedCache distributedCache, IHttpClientFactory httpClientFactory) : PermissionChecker(httpContextAccessor, distributedCache)
{ {
private readonly RemotePermissionCheckerOptions _remotePermissionCheckerOptions = options.Value;
public override async Task<bool> IsGrantedAsync(int roleId, string permissionName, string? resourceType = null, string? resourceId = null) public override async Task<bool> IsGrantedAsync(int roleId, string permissionName, string? resourceType = null, string? resourceId = null)
{ {
string? accessToken = await HttpContext.GetTokenAsync("access_token"); string? accessToken = await HttpContext.GetTokenAsync("access_token");
@ -21,7 +19,7 @@ public class RemotePermissionChecker(IHttpContextAccessor httpContextAccessor, I
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
httpClient.BaseAddress = new Uri(_remotePermissionCheckerOptions.ApiEndpoint); httpClient.BaseAddress = new Uri("http://identityservice");
Dictionary<string, string?> parameters = new() Dictionary<string, string?> parameters = new()
{ {

View File

@ -1,6 +0,0 @@
namespace HelloShop.ServiceDefaults.Authorization;
public class RemotePermissionCheckerOptions
{
public string ApiEndpoint { get; set; } = default!;
}

View File

@ -65,10 +65,8 @@ public static class PermissionExtensions
return routeGroup; return routeGroup;
} }
public static IServiceCollection AddRemotePermissionChecker(this IServiceCollection services, Action<RemotePermissionCheckerOptions> configureOptions) public static IServiceCollection AddRemotePermissionChecker(this IServiceCollection services)
{ {
services.Configure(configureOptions);
services.AddTransient<IPermissionChecker, RemotePermissionChecker>(); services.AddTransient<IPermissionChecker, RemotePermissionChecker>();
return services; return services;