diff --git a/Blog.Core.Gateway/Blog.Core.Gateway.csproj b/Blog.Core.Gateway/Blog.Core.Gateway.csproj index 8af7a7e..a21feb4 100644 --- a/Blog.Core.Gateway/Blog.Core.Gateway.csproj +++ b/Blog.Core.Gateway/Blog.Core.Gateway.csproj @@ -12,6 +12,14 @@ + + + + + + + + diff --git a/Blog.Core.Gateway/Blog.Core.Gateway.xml b/Blog.Core.Gateway/Blog.Core.Gateway.xml index 41507d7..3454334 100644 --- a/Blog.Core.Gateway/Blog.Core.Gateway.xml +++ b/Blog.Core.Gateway/Blog.Core.Gateway.xml @@ -51,50 +51,5 @@ │ 作 者:anson zhang └──────────────────────────────────────────────────────────────┘ - - - Nacos配置文件变更事件 - - - - - Nacos 配置文件监听事件 - - - - - - - - - - - - - - - 执行 - - - - - - - 停止 - - - - - - - 配置监听事件 - - - - - 收到配置文件变更 - - - diff --git a/Blog.Core.Gateway/Extensions/CustomOcelotSetup.cs b/Blog.Core.Gateway/Extensions/CustomOcelotSetup.cs index f04df2a..b197c82 100644 --- a/Blog.Core.Gateway/Extensions/CustomOcelotSetup.cs +++ b/Blog.Core.Gateway/Extensions/CustomOcelotSetup.cs @@ -16,11 +16,12 @@ namespace Blog.Core.Gateway.Extensions { if (services == null) throw new ArgumentNullException(nameof(services)); - var basePath = AppContext.BaseDirectory; - services.AddAuthentication_JWTSetup(); - services.AddOcelot().AddDelegatingHandler().AddNacosDiscovery().AddPolly(); - //.AddConsul().AddPolly(); + services.AddOcelot() + .AddDelegatingHandler() + //.AddNacosDiscovery() + //.AddConsul() + .AddPolly(); } public static async Task UseCustomOcelotMildd(this IApplicationBuilder app) diff --git a/Blog.Core.Gateway/Extensions/CustomSwaggerSetup.cs b/Blog.Core.Gateway/Extensions/CustomSwaggerSetup.cs index 92956ff..033feeb 100644 --- a/Blog.Core.Gateway/Extensions/CustomSwaggerSetup.cs +++ b/Blog.Core.Gateway/Extensions/CustomSwaggerSetup.cs @@ -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.Options; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.Filters; +using Swashbuckle.AspNetCore.SwaggerUI; using System; using System.Collections.Generic; using System.IO; using System.Reflection; +using static Blog.Core.Extensions.CustomApiVersion; namespace Blog.Core.Gateway.Extensions { 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 streamHtml) { if (app == null) throw new ArgumentNullException(nameof(app)); var apis = new List { "blog-svc" }; - app.UseMvc().UseSwagger(); - app.UseSwaggerUI(options => + app.UseSwagger(); + app.UseSwaggerUI(c => { - options.SwaggerEndpoint($"/swagger/v1/swagger.json", $"Blog.Core.Gateway-v1"); - + c.SwaggerEndpoint($"/swagger/v1/swagger.json", "gateway"); apis.ForEach(m => { - options.SwaggerEndpoint($"/swagger/apiswg/{m}/swagger.json", m); - options.IndexStream = () => app.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Blog.Core.ApiGateway.index.html"); + c.SwaggerEndpoint($"/swagger/apiswg/{m}/swagger.json", m); }); - options.RoutePrefix = ""; + + if (streamHtml.Invoke() == null) + { + var msg = "index.html的属性,必须设置为嵌入的资源"; + throw new Exception(msg); + } + + c.IndexStream = streamHtml; + + c.RoutePrefix = ""; }); } diff --git a/Blog.Core.Gateway/Helper/CustomJwtTokenAuthMiddleware.cs b/Blog.Core.Gateway/Helper/CustomJwtTokenAuthMiddleware.cs index b00db95..f9120ec 100644 --- a/Blog.Core.Gateway/Helper/CustomJwtTokenAuthMiddleware.cs +++ b/Blog.Core.Gateway/Helper/CustomJwtTokenAuthMiddleware.cs @@ -1,16 +1,9 @@ -using System; -using System.Net; -using System.Linq; -using System.Collections.Generic; -using System.Threading.Tasks; +using System.Net; using System.Text.RegularExpressions; using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Http; using Blog.Core.Common; using Blog.Core.Common.Caches; using Blog.Core.Common.Helper; -using Nacos.V2; -using Newtonsoft.Json.Linq; namespace Blog.Core.AuthHelper { @@ -23,7 +16,6 @@ namespace Blog.Core.AuthHelper { private readonly ICaching _cache; - private readonly INacosNamingService NacosServClient; /// /// 验证方案提供对象 @@ -36,13 +28,11 @@ namespace Blog.Core.AuthHelper 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; _next = next; Schemes = schemes; - List Permissions = _cache.Cof_AsyncGetICaching>("Permissions", GetPermitionData, 10).GetAwaiter().GetResult(); } /// @@ -66,7 +56,7 @@ namespace Blog.Core.AuthHelper return; } - List Permissions= await _cache.Cof_AsyncGetICaching>("Permissions", GetPermitionData, 10); + List Permissions= new(); httpContext.Features.Set(new AuthenticationFeature { @@ -126,28 +116,6 @@ namespace Blog.Core.AuthHelper await _next.Invoke(httpContext); } - private async Task> 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>(); - return perJt["data"].ToObject>(); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - } - - return null; - } - /// /// 返回相应 /// diff --git a/Blog.Core.Gateway/Helper/OcelotConfigurationTask.cs b/Blog.Core.Gateway/Helper/OcelotConfigurationTask.cs deleted file mode 100644 index a95df86..0000000 --- a/Blog.Core.Gateway/Helper/OcelotConfigurationTask.cs +++ /dev/null @@ -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 -{ - /// - /// Nacos配置文件变更事件 - /// - public class OcelotConfigurationTask : BackgroundService - { - private readonly INacosConfigService _configClient; - private readonly INacosNamingService _servClient; - /// - /// Nacos 配置文件监听事件 - /// - private OcelotConfigListener nacosConfigListener = new OcelotConfigListener(); - private AppConfigListener AppConfigListener = new AppConfigListener(); - private string OcelotConfig = ""; - private string OcelotConfigGroup = ""; - private string AppConfig = ""; - private string AppConfigGroup = ""; - - - /// - /// - /// - /// - /// - /// - /// - /// - 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(); - } - - - - /// - /// 执行 - /// - /// - /// - 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) - { - } - } - - /// - /// 停止 - /// - /// - /// - 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); - } - } - - /// - /// 配置监听事件 - /// - public class OcelotConfigListener : IListener - { - public IInternalConfigurationRepository internalConfigurationRepo { get; set; } - public IInternalConfigurationCreator internalConfigurationCreator { get; set; } - /// - /// 收到配置文件变更 - /// - /// - public void ReceiveConfigInfo(string configInfo) - { - Task.Run(async () => - { - FileConfiguration filecfg = JToken.Parse(configInfo).ToObject(); - 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; - } - } -} diff --git a/Blog.Core.Gateway/Startup.cs b/Blog.Core.Gateway/Startup.cs index 552b4ef..1a37cc9 100644 --- a/Blog.Core.Gateway/Startup.cs +++ b/Blog.Core.Gateway/Startup.cs @@ -1,14 +1,10 @@ using Blog.Core.AuthHelper; using Blog.Core.Common; +using Blog.Core.Common.Caches; using Blog.Core.Extensions; using Blog.Core.Gateway.Extensions; using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Nacos.V2.DependencyInjection; +using System.Reflection; namespace Blog.Core.AdminMvc { @@ -34,17 +30,10 @@ namespace Blog.Core.AdminMvc { services.AddSingleton(new AppSettings(Configuration)); - services.AddAuthentication_JWTSetup(); - services.AddAuthentication() .AddScheme(Permissions.GWName, _ => { }); - services.AddNacosV2Config(Configuration, null, "nacosConfig"); - services.AddNacosV2Naming(Configuration, null, "nacos"); - services.AddHostedService(); - - services.AddCustomSwaggerSetup(); services.AddControllers(); @@ -53,6 +42,10 @@ namespace Blog.Core.AdminMvc services.AddCorsSetup(); + services.AddMemoryCache(); + services.AddDistributedMemoryCache(); + services.AddSingleton(); + services.AddCustomOcelotSetup(); } @@ -69,7 +62,7 @@ namespace Blog.Core.AdminMvc app.UseAuthentication(); app.UseAuthorization(); - app.UseCustomSwaggerMildd(); + app.UseCustomSwaggerMildd(() => Assembly.GetExecutingAssembly().GetManifestResourceStream("Blog.Core.Gateway.index.html")); app.UseCors(AppSettings.app(new string[] { "Startup", "Cors", "PolicyName" })); @@ -79,7 +72,7 @@ namespace Blog.Core.AdminMvc }); app.UseMiddleware(); - + app.UseCustomOcelotMildd().Wait(); } } diff --git a/Blog.Core.Gateway/appsettings.gw.json b/Blog.Core.Gateway/appsettings.gw.json index 33b99ee..93e6463 100644 --- a/Blog.Core.Gateway/appsettings.gw.json +++ b/Blog.Core.Gateway/appsettings.gw.json @@ -1,6 +1,5 @@ { "Logging": { - "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" @@ -21,6 +20,11 @@ "IPs": "http://127.0.0.1:2364,http://localhost:2364" } }, + "Redis": { + "Enable": false, + "ConnectionString": "127.0.0.1:6379", + "InstanceName": "" //前缀 + }, "Audience": { "Secret": "sdfsdfsrty45634kkhllghtdgdfss345t678fs", "SecretFile": "C:\\my-file\\blog.core.audience.secret.txt", @@ -31,73 +35,17 @@ { "url": "/" }, { "url": "/illagal/****" }, { "url": "/api3/****" }, - { "url": "/baseapi/swagger.json" } + { "url": "/baseapi/swagger.json" }, + { "url": "/swagger/v1/swagger.json" }, + { "url": "/swagger/apiswg/blog-svc/swagger.json" } ], "BlackList": [ { "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": { "Endpoint": "http://*******:9328", "uid": "root", "pwd": "*****", "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\"}" } - - - } diff --git a/Blog.Core.Gateway/ocelot.Development.json b/Blog.Core.Gateway/ocelot.Development.json index 6af5171..589a5a6 100644 --- a/Blog.Core.Gateway/ocelot.Development.json +++ b/Blog.Core.Gateway/ocelot.Development.json @@ -49,11 +49,6 @@ ], "GlobalConfiguration": { - "BaseUrl": "http://localhost:9000", - "ServiceDiscoveryProvider": { - "Host": "localhost", - "Port": 8500, - "Type": "Consul" - } + "BaseUrl": "http://localhost:9000" } } \ No newline at end of file