feat:更新gateway,去除nacos相关配置

This commit is contained in:
anjoy8 2023-12-03 18:16:27 +08:00
parent c4a6c84d96
commit 5f132f0386
9 changed files with 54 additions and 321 deletions

View File

@ -12,6 +12,14 @@
<Compile Remove="Helper\HeaderDelegatingHandler.cs" /> <Compile Remove="Helper\HeaderDelegatingHandler.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Remove="index.html" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="index.html" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" NoWarn="NU1605" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" NoWarn="NU1605" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.0" NoWarn="NU1605" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.0" NoWarn="NU1605" />

View File

@ -51,50 +51,5 @@
│ 作 者anson zhang │ 作 者anson zhang
└──────────────────────────────────────────────────────────────┘ └──────────────────────────────────────────────────────────────┘
</member> </member>
<member name="T:ApiGateway.Helper.OcelotConfigurationTask">
<summary>
Nacos配置文件变更事件
</summary>
</member>
<member name="F:ApiGateway.Helper.OcelotConfigurationTask.nacosConfigListener">
<summary>
Nacos 配置文件监听事件
</summary>
</member>
<member name="M:ApiGateway.Helper.OcelotConfigurationTask.#ctor(Nacos.V2.INacosNamingService,Nacos.V2.INacosConfigService,System.IServiceProvider,Ocelot.Configuration.Repository.IInternalConfigurationRepository,Ocelot.Configuration.Creator.IInternalConfigurationCreator)">
<summary>
</summary>
<param name="serv"></param>
<param name="configClient"></param>
<param name="serviceProvider"></param>
<param name="_internalConfigurationRepo"></param>
<param name="_internalConfigurationCreator"></param>
</member>
<member name="M:ApiGateway.Helper.OcelotConfigurationTask.ExecuteAsync(System.Threading.CancellationToken)">
<summary>
执行
</summary>
<param name="stoppingToken"></param>
<returns></returns>
</member>
<member name="M:ApiGateway.Helper.OcelotConfigurationTask.StopAsync(System.Threading.CancellationToken)">
<summary>
停止
</summary>
<param name="cancellationToken"></param>
<returns></returns>
</member>
<member name="T:ApiGateway.Helper.OcelotConfigListener">
<summary>
配置监听事件
</summary>
</member>
<member name="M:ApiGateway.Helper.OcelotConfigListener.ReceiveConfigInfo(System.String)">
<summary>
收到配置文件变更
</summary>
<param name="configInfo"></param>
</member>
</members> </members>
</doc> </doc>

View File

@ -16,11 +16,12 @@ namespace Blog.Core.Gateway.Extensions
{ {
if (services == null) throw new ArgumentNullException(nameof(services)); if (services == null) throw new ArgumentNullException(nameof(services));
var basePath = AppContext.BaseDirectory;
services.AddAuthentication_JWTSetup(); services.AddAuthentication_JWTSetup();
services.AddOcelot().AddDelegatingHandler<CustomResultHandler>().AddNacosDiscovery().AddPolly(); services.AddOcelot()
//.AddConsul().AddPolly(); .AddDelegatingHandler<CustomResultHandler>()
//.AddNacosDiscovery()
//.AddConsul()
.AddPolly();
} }
public static async Task<IApplicationBuilder> UseCustomOcelotMildd(this IApplicationBuilder app) public static async Task<IApplicationBuilder> UseCustomOcelotMildd(this IApplicationBuilder app)

View File

@ -1,11 +1,16 @@
using Microsoft.AspNetCore.Builder; using Blog.Core.Common;
using Blog.Core.Extensions.Middlewares;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters; using Swashbuckle.AspNetCore.Filters;
using Swashbuckle.AspNetCore.SwaggerUI;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using static Blog.Core.Extensions.CustomApiVersion;
namespace Blog.Core.Gateway.Extensions namespace Blog.Core.Gateway.Extensions
{ {
public static class CustomSwaggerSetup public static class CustomSwaggerSetup
@ -44,23 +49,30 @@ namespace Blog.Core.Gateway.Extensions
}); });
} }
public static void UseCustomSwaggerMildd(this IApplicationBuilder app) public static void UseCustomSwaggerMildd(this IApplicationBuilder app, Func<Stream> streamHtml)
{ {
if (app == null) throw new ArgumentNullException(nameof(app)); if (app == null) throw new ArgumentNullException(nameof(app));
var apis = new List<string> { "blog-svc" }; var apis = new List<string> { "blog-svc" };
app.UseMvc().UseSwagger(); app.UseSwagger();
app.UseSwaggerUI(options => app.UseSwaggerUI(c =>
{ {
options.SwaggerEndpoint($"/swagger/v1/swagger.json", $"Blog.Core.Gateway-v1"); c.SwaggerEndpoint($"/swagger/v1/swagger.json", "gateway");
apis.ForEach(m => apis.ForEach(m =>
{ {
options.SwaggerEndpoint($"/swagger/apiswg/{m}/swagger.json", m); c.SwaggerEndpoint($"/swagger/apiswg/{m}/swagger.json", m);
options.IndexStream = () => app.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Blog.Core.ApiGateway.index.html");
}); });
options.RoutePrefix = "";
if (streamHtml.Invoke() == null)
{
var msg = "index.html的属性必须设置为嵌入的资源";
throw new Exception(msg);
}
c.IndexStream = streamHtml;
c.RoutePrefix = "";
}); });
} }

View File

@ -1,16 +1,9 @@
using System; using System.Net;
using System.Net;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Blog.Core.Common; using Blog.Core.Common;
using Blog.Core.Common.Caches; using Blog.Core.Common.Caches;
using Blog.Core.Common.Helper; using Blog.Core.Common.Helper;
using Nacos.V2;
using Newtonsoft.Json.Linq;
namespace Blog.Core.AuthHelper namespace Blog.Core.AuthHelper
{ {
@ -23,7 +16,6 @@ namespace Blog.Core.AuthHelper
{ {
private readonly ICaching _cache; private readonly ICaching _cache;
private readonly INacosNamingService NacosServClient;
/// <summary> /// <summary>
/// 验证方案提供对象 /// 验证方案提供对象
@ -36,13 +28,11 @@ namespace Blog.Core.AuthHelper
private readonly RequestDelegate _next; private readonly RequestDelegate _next;
public CustomJwtTokenAuthMiddleware(INacosNamingService serv, RequestDelegate next, IAuthenticationSchemeProvider schemes, AppSettings appset,ICaching cache) public CustomJwtTokenAuthMiddleware(RequestDelegate next, IAuthenticationSchemeProvider schemes, AppSettings appset,ICaching cache)
{ {
NacosServClient = serv;
_cache = cache; _cache = cache;
_next = next; _next = next;
Schemes = schemes; Schemes = schemes;
List<PermissionItem> Permissions = _cache.Cof_AsyncGetICaching<List<PermissionItem>>("Permissions", GetPermitionData, 10).GetAwaiter().GetResult();
} }
/// <summary> /// <summary>
@ -66,7 +56,7 @@ namespace Blog.Core.AuthHelper
return; return;
} }
List<PermissionItem> Permissions= await _cache.Cof_AsyncGetICaching<List<PermissionItem>>("Permissions", GetPermitionData, 10); List<PermissionItem> Permissions= new();
httpContext.Features.Set<IAuthenticationFeature>(new AuthenticationFeature httpContext.Features.Set<IAuthenticationFeature>(new AuthenticationFeature
{ {
@ -126,28 +116,6 @@ namespace Blog.Core.AuthHelper
await _next.Invoke(httpContext); await _next.Invoke(httpContext);
} }
private async Task<List<PermissionItem>> GetPermitionData()
{
try
{
string PermissionServName = AppSettings.GetValue("ApiGateWay:PermissionServName");
string PermissionServGroup = AppSettings.GetValue("ApiGateWay:PermissionServGroup");
string PermissionServUrl = AppSettings.GetValue("ApiGateWay:PermissionServUrl");
string requestdata = await NacosServClient.Cof_NaoceGet(PermissionServName, PermissionServGroup, PermissionServUrl);
if (string.IsNullOrEmpty(requestdata)) return null;
JToken perJt = JToken.Parse(requestdata);
if(perJt["response"]!=null) return perJt["response"].ToObject<List<PermissionItem>>();
return perJt["data"].ToObject<List<PermissionItem>>();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return null;
}
/// <summary> /// <summary>
/// 返回相应 /// 返回相应
/// </summary> /// </summary>

View File

@ -1,147 +0,0 @@

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Nacos.V2;
using System;
using System.Threading;
using System.Threading.Tasks;
using Blog.Core.Common.Helper;
using Ocelot.Configuration.Repository;
using Ocelot.Configuration.Creator;
using Newtonsoft.Json.Linq;
using Ocelot.Configuration.File;
using Blog.Core.Common;
namespace ApiGateway.Helper
{
/// <summary>
/// Nacos配置文件变更事件
/// </summary>
public class OcelotConfigurationTask : BackgroundService
{
private readonly INacosConfigService _configClient;
private readonly INacosNamingService _servClient;
/// <summary>
/// Nacos 配置文件监听事件
/// </summary>
private OcelotConfigListener nacosConfigListener = new OcelotConfigListener();
private AppConfigListener AppConfigListener = new AppConfigListener();
private string OcelotConfig = "";
private string OcelotConfigGroup = "";
private string AppConfig = "";
private string AppConfigGroup = "";
/// <summary>
///
/// </summary>
/// <param name="serv"></param>
/// <param name="configClient"></param>
/// <param name="serviceProvider"></param>
/// <param name="_internalConfigurationRepo"></param>
/// <param name="_internalConfigurationCreator"></param>
public OcelotConfigurationTask(INacosNamingService serv, INacosConfigService configClient, IServiceProvider serviceProvider, IInternalConfigurationRepository _internalConfigurationRepo, IInternalConfigurationCreator _internalConfigurationCreator)
{
_configClient = configClient;
_servClient = serv;
nacosConfigListener.internalConfigurationRepo = _internalConfigurationRepo;
nacosConfigListener.internalConfigurationCreator = _internalConfigurationCreator;
OcelotConfig = AppSettings.GetValue("ApiGateWay:OcelotConfig");
OcelotConfigGroup = AppSettings.GetValue("ApiGateWay:OcelotConfigGroup");
AppConfig = AppSettings.GetValue("ApiGateWay:AppConfig");
AppConfigGroup = AppSettings.GetValue("ApiGateWay:AppConfigGroup");
string OcelotCfg = configClient.GetConfig(OcelotConfig, OcelotConfigGroup, 10000).GetAwaiter().GetResult();
nacosConfigListener.ReceiveConfigInfo(OcelotCfg);
string AppCfg= configClient.GetConfig(AppConfig, AppConfigGroup, 10000).GetAwaiter().GetResult();
AppConfigListener.ReceiveConfigInfo(AppCfg);
//string sss = serv.Cof_NaoceGet("fld-cloud-datax", "DEFAULT_GROUP", "/api/base/deviceList?limit=10&page=1").GetAwaiter().GetResult();
}
/// <summary>
/// 执行
/// </summary>
/// <param name="stoppingToken"></param>
/// <returns></returns>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
// Add listener OcelotConfig.json"
await _configClient.AddListener(OcelotConfig, OcelotConfigGroup, nacosConfigListener);
await _configClient.AddListener(AppConfig, AppConfigGroup, AppConfigListener);
}
catch (Exception)
{
}
}
/// <summary>
/// 停止
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override async Task StopAsync(CancellationToken cancellationToken)
{
// Remove listener
await _configClient.RemoveListener(OcelotConfig, OcelotConfigGroup, nacosConfigListener);
await _configClient.RemoveListener(AppConfig, AppConfigGroup, AppConfigListener);
await base.StopAsync(cancellationToken);
}
}
/// <summary>
/// 配置监听事件
/// </summary>
public class OcelotConfigListener : IListener
{
public IInternalConfigurationRepository internalConfigurationRepo { get; set; }
public IInternalConfigurationCreator internalConfigurationCreator { get; set; }
/// <summary>
/// 收到配置文件变更
/// </summary>
/// <param name="configInfo"></param>
public void ReceiveConfigInfo(string configInfo)
{
Task.Run(async () =>
{
FileConfiguration filecfg = JToken.Parse(configInfo).ToObject<FileConfiguration>();
var internalConfiguration = await internalConfigurationCreator.Create(filecfg);
if (!internalConfiguration.IsError)
{
internalConfigurationRepo.AddOrReplace(internalConfiguration.Data);
}
});
}
}
public class AppConfigListener : IListener
{
public void ReceiveConfigInfo(string configInfo)
{
var _configurationBuilder = new ConfigurationBuilder();
_configurationBuilder.Sources.Clear();
var buffer = System.Text.Encoding.Default.GetBytes(configInfo);
System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
_configurationBuilder.AddJsonStream(ms);
var configuration = _configurationBuilder.Build();
ms.Dispose();
// 读取配置 将nacos配置中心读取到的配置 替换掉.net core 内存中的 configuration
// 当前监听到配置配置 应该重新断开 重连 刷新等一些中间件操作
// 比如 mq redis 等其他跟配置相关的中间件
JsonConfigSettings.Configuration = configuration;
AppSettings.Configuration = configuration;
}
}
}

View File

@ -1,14 +1,10 @@
using Blog.Core.AuthHelper; using Blog.Core.AuthHelper;
using Blog.Core.Common; using Blog.Core.Common;
using Blog.Core.Common.Caches;
using Blog.Core.Extensions; using Blog.Core.Extensions;
using Blog.Core.Gateway.Extensions; using Blog.Core.Gateway.Extensions;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder; using System.Reflection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Nacos.V2.DependencyInjection;
namespace Blog.Core.AdminMvc namespace Blog.Core.AdminMvc
{ {
@ -34,17 +30,10 @@ namespace Blog.Core.AdminMvc
{ {
services.AddSingleton(new AppSettings(Configuration)); services.AddSingleton(new AppSettings(Configuration));
services.AddAuthentication_JWTSetup();
services.AddAuthentication() services.AddAuthentication()
.AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(Permissions.GWName, _ => { }); .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(Permissions.GWName, _ => { });
services.AddNacosV2Config(Configuration, null, "nacosConfig");
services.AddNacosV2Naming(Configuration, null, "nacos");
services.AddHostedService<ApiGateway.Helper.OcelotConfigurationTask>();
services.AddCustomSwaggerSetup(); services.AddCustomSwaggerSetup();
services.AddControllers(); services.AddControllers();
@ -53,6 +42,10 @@ namespace Blog.Core.AdminMvc
services.AddCorsSetup(); services.AddCorsSetup();
services.AddMemoryCache();
services.AddDistributedMemoryCache();
services.AddSingleton<ICaching, Caching>();
services.AddCustomOcelotSetup(); services.AddCustomOcelotSetup();
} }
@ -69,7 +62,7 @@ namespace Blog.Core.AdminMvc
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.UseCustomSwaggerMildd(); app.UseCustomSwaggerMildd(() => Assembly.GetExecutingAssembly().GetManifestResourceStream("Blog.Core.Gateway.index.html"));
app.UseCors(AppSettings.app(new string[] { "Startup", "Cors", "PolicyName" })); app.UseCors(AppSettings.app(new string[] { "Startup", "Cors", "PolicyName" }));
@ -79,7 +72,7 @@ namespace Blog.Core.AdminMvc
}); });
app.UseMiddleware<CustomJwtTokenAuthMiddleware>(); app.UseMiddleware<CustomJwtTokenAuthMiddleware>();
app.UseCustomOcelotMildd().Wait(); app.UseCustomOcelotMildd().Wait();
} }
} }

View File

@ -1,6 +1,5 @@
{ {
"Logging": { "Logging": {
"IncludeScopes": false,
"Debug": { "Debug": {
"LogLevel": { "LogLevel": {
"Default": "Warning" "Default": "Warning"
@ -21,6 +20,11 @@
"IPs": "http://127.0.0.1:2364,http://localhost:2364" "IPs": "http://127.0.0.1:2364,http://localhost:2364"
} }
}, },
"Redis": {
"Enable": false,
"ConnectionString": "127.0.0.1:6379",
"InstanceName": "" //
},
"Audience": { "Audience": {
"Secret": "sdfsdfsrty45634kkhllghtdgdfss345t678fs", "Secret": "sdfsdfsrty45634kkhllghtdgdfss345t678fs",
"SecretFile": "C:\\my-file\\blog.core.audience.secret.txt", "SecretFile": "C:\\my-file\\blog.core.audience.secret.txt",
@ -31,73 +35,17 @@
{ "url": "/" }, { "url": "/" },
{ "url": "/illagal/****" }, { "url": "/illagal/****" },
{ "url": "/api3/****" }, { "url": "/api3/****" },
{ "url": "/baseapi/swagger.json" } { "url": "/baseapi/swagger.json" },
{ "url": "/swagger/v1/swagger.json" },
{ "url": "/swagger/apiswg/blog-svc/swagger.json" }
], ],
"BlackList": [ "BlackList": [
{ "url": "/favicon.ico" } { "url": "/favicon.ico" }
], ],
"ApiGateWay": {
"OcelotConfig": "OcelotConfig.json",
"OcelotConfigGroup": "DEFAULT_GROUP",
"AppConfig": "****.****.Gateway.json",
"AppConfigGroup": "DEFAULT_GROUP",
"PermissionServName": "****.****.Api",
"PermissionServGroup": "DEFAULT_GROUP",
"PermissionServUrl": "/api/Permission/GetPermissionlist"
},
"Influxdb": { "Influxdb": {
"Endpoint": "http://*******:9328", "Endpoint": "http://*******:9328",
"uid": "root", "uid": "root",
"pwd": "*****", "pwd": "*****",
"dbname": "mndata" "dbname": "mndata"
},
"nacos": {
"ServerAddresses": [ "http://******:8848/" ],
"ServiceName": "*****.****.Gateway",
"DefaultTimeOut": 15000,
"Namespace": "****",
"ListenInterval": 1000,
"GroupName": "DEFAULT_GROUP",
"ClusterName": "DEFAULT",
"Ip": "",
"PreferredNetworks": "",
"Port": 8090,
"Weight": 100,
"RegisterEnabled": true,
"InstanceEnabled": true,
"Ephemeral": true,
"Secure": false,
"AccessKey": "",
"SecretKey": "",
"UserName": "****",
"Password": "*****",
"NamingUseRpc": true,
"NamingLoadCacheAtStart": "",
"LBStrategy": "WeightRandom",
"Metadata": {
"aa": "bb",
"cc": "dd",
"endpoint33": "******:8090"
}
},
"nacosConfig": {
"ServiceName": "*****.*****.Gateway",
"Optional": false,
"DataId": "options1",
"Tenant": "******",
"Group": "DEFAULT_GROUP",
"Namespace": "*****",
"ServerAddresses": [ "http://******:8848/" ],
"UserName": "****",
"Password": "*****",
"AccessKey": "",
"SecretKey": "",
"EndPoint": "",
"ConfigUseRpc": true,
"ConfigFilterAssemblies": [ "apigateway" ],
"ConfigFilterExtInfo": "{\"JsonPaths\":[\"ConnectionStrings.Default\"],\"Other\":\"xxxxxx\"}"
} }
} }

View File

@ -49,11 +49,6 @@
], ],
"GlobalConfiguration": { "GlobalConfiguration": {
"BaseUrl": "http://localhost:9000", "BaseUrl": "http://localhost:9000"
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"Type": "Consul"
}
} }
} }