Commit c46b4acc by 赵剑炜

正式版1.0

parent 6a1ca82e
......@@ -6,11 +6,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{B76348CD-F49
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Provider.Nacos", "src\Ocelot.Provider.Nacos\Ocelot.Provider.Nacos.csproj", "{284367EA-EC93-4060-ABE7-3EF93A5A888C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "demo", "demo", "{7A2BFC89-057F-4F8D-ADB7-C7D122B160EF}"
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GateWay", "GateWay", "{7A2BFC89-057F-4F8D-ADB7-C7D122B160EF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiGatewayDemo", "demo\ApiGatewayDemo\ApiGatewayDemo.csproj", "{179D0A0F-AAC3-4322-92DE-008F91554389}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProductApi", "demo\ProductApi\ProductApi.csproj", "{F1AA9A81-CBB6-4D8E-9FC4-45C7355AF8CA}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiGateway", "gateWay\ApiGateway\ApiGateway.csproj", "{179D0A0F-AAC3-4322-92DE-008F91554389}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
......@@ -26,10 +24,6 @@ Global
{179D0A0F-AAC3-4322-92DE-008F91554389}.Debug|Any CPU.Build.0 = Debug|Any CPU
{179D0A0F-AAC3-4322-92DE-008F91554389}.Release|Any CPU.ActiveCfg = Release|Any CPU
{179D0A0F-AAC3-4322-92DE-008F91554389}.Release|Any CPU.Build.0 = Release|Any CPU
{F1AA9A81-CBB6-4D8E-9FC4-45C7355AF8CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F1AA9A81-CBB6-4D8E-9FC4-45C7355AF8CA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F1AA9A81-CBB6-4D8E-9FC4-45C7355AF8CA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F1AA9A81-CBB6-4D8E-9FC4-45C7355AF8CA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......@@ -37,6 +31,8 @@ Global
GlobalSection(NestedProjects) = preSolution
{284367EA-EC93-4060-ABE7-3EF93A5A888C} = {B76348CD-F496-4B6E-A915-82A342AA5150}
{179D0A0F-AAC3-4322-92DE-008F91554389} = {7A2BFC89-057F-4F8D-ADB7-C7D122B160EF}
{F1AA9A81-CBB6-4D8E-9FC4-45C7355AF8CA} = {7A2BFC89-057F-4F8D-ADB7-C7D122B160EF}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1F19CAA0-6CA7-4118-9E91-506DBA12651C}
EndGlobalSection
EndGlobal
{
"profiles": {
"ApiGatewayDemo": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:4422",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
\ No newline at end of file
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"nacos": {
"ServerAddresses": [ "http://192.168.2.54:8849" ],
"ServiceName": "JYZB3.0",
"DefaultTimeOut": 15000,
//自定义Namespace的Id
"Namespace": "8e6c6559-3b86-4dfa-b817-ad38da91ca37",
"GroupName": "DEFAULT_GROUP",
"ClusterName": "DEFAULT",
"ListenInterval": 1000,
"RegisterEnabled": true,
"InstanceEnabled": true,
"LBStrategy": "WeightRandom",
"NamingUseRpc": true
},
"Routes": [
{
"ServiceName": "JunmpPoliceStation74",
"DownstreamHostAndPorts": [
{
"Host": "192.168.3.188",
"Port": 5000,
"Metadata": {
"weight": "9"
}
},
{
"Host": "192.168.2.54",
"Port": 5000,
"Metadata": {
"weight": "1"
}
}
],
// Uri方案,http、https
"DownstreamScheme": "http",
// 下游(服务提供方)服务路由模板
"DownstreamPathTemplate": "/api/{everything}",
// 上游(客户端,服务消费方)请求路由模板
"UpstreamPathTemplate": "/service/{everything}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"LoadBalancerOptions": {
"Type": "CustomerBalancer"
},
"UseServiceDiscovery": true
}
],
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Type": "Nacos"
}
}
}
{
// 转发路由,数组中的每个元素都是某个服务的一组路由转发规则
"Routes": [
{
"ServiceName": "JunmpPoliceStation74",
"DownstreamHostAndPorts": [
{
"Host": "192.168.3.188",
"Port": 5000,
"Metadata": {
"weight": "9"
}
},
{
"Host": "192.168.2.54",
"Port": 5000,
"Metadata": {
"weight": "1"
}
}
],
// Uri方案,http、https
"DownstreamScheme": "http",
// 下游(服务提供方)服务路由模板
"DownstreamPathTemplate": "/api/{everything}",
// 上游(客户端,服务消费方)请求路由模板
"UpstreamPathTemplate": "/service/{everything}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"LoadBalancerOptions": {
"Type": "RoundRobinWithWeightedHosts"
},
"UseServiceDiscovery": true
}
],
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Type": "Nacos"
}
}
}
\ No newline at end of file
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "7.0.4",
"commands": [
"dotnet-ef"
]
}
}
}
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<AssemblyName>ApiGatewayDemo</AssemblyName>
<TargetFramework>net6.0</TargetFramework>
<AssemblyName>ApiGateway</AssemblyName>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="nacos-sdk-csharp" Version="1.3.4" />
<PackageReference Include="nacos-sdk-csharp.AspNetCore" Version="1.3.4" />
<PackageReference Include="nacos-sdk-csharp.Extensions.Configuration" Version="1.3.4" />
<PackageReference Include="nacos-sdk-csharp.IniParser" Version="1.3.4" />
<PackageReference Include="nacos-sdk-csharp.YamlParser" Version="1.3.4" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.2.3" />
<PackageReference Include="Ocelot" Version="18.0.0" />
</ItemGroup>
......@@ -14,11 +20,16 @@
<ProjectReference Include="..\..\src\Ocelot.Provider.Nacos\Ocelot.Provider.Nacos.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="ocelotconfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Condition="'$(ExcludeConfigFilesFromBuildOutput)'!='true'" Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Properties\launchSettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Google.Protobuf.WellKnownTypes;
......@@ -8,25 +9,43 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ApiGatewayDemo
namespace ApiGateway
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
var logger = NLog.Web.NLogBuilder.ConfigureNLog(AppContext.BaseDirectory + "nlog.config.xml").GetCurrentClassLogger();
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
logger.Error(ex);
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseNacosConfig(section: "Nacos", parser: null, logAction: null)
.ConfigureWebHostDefaults(webBuilder =>
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true)
.Build();
webBuilder.UseStartup<Startup>();
webBuilder.UseConfiguration(config);
}).ConfigureAppConfiguration(builder=> {
builder.AddJsonFile("appsettings.json", true, true);
//builder.AddJsonFile("ocelotconfig.json", true, true);
});
}
}
{
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "http://192.168.3.188:3993/nacos",
"applicationUrl": "http://192.168.3.1:5000;http://192.168.10.88:5000;http://localhost:5001;http://localhost:5000;"
},
"WSL": {
"commandName": "WSL2",
"launchBrowser": true,
"launchUrl": "http://localhost:6003",
"environmentVariables": {
"ASPNETCORE_URLS": "http://localhost:6003"
},
"distributionName": ""
},
"ApiGateway": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:6003"
}
},
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:28174/",
"sslPort": 44389
}
}
}
\ No newline at end of file
......@@ -2,12 +2,14 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ApiGateway;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Nacos.AspNetCore.V2;
using Ocelot.Configuration;
using Ocelot.DependencyInjection;
using Ocelot.LoadBalancer.LoadBalancers;
......@@ -16,7 +18,7 @@ using Ocelot.Provider.Nacos;
using Ocelot.ServiceDiscovery;
using Ocelot.ServiceDiscovery.Providers;
namespace ApiGatewayDemo
namespace ApiGateway
{
public class Startup
{
......@@ -26,34 +28,19 @@ namespace ApiGatewayDemo
}
public IConfiguration Configuration { get; }
Func<IServiceProvider, DownstreamRoute, IServiceDiscoveryProvider, CustomerBalancer> loadBalancerFactoryFunc = (serviceProvider, Route, serviceDiscoveryProvider) => new CustomerBalancer(serviceDiscoveryProvider.Get);
Func<IServiceProvider, DownstreamRoute, IServiceDiscoveryProvider, WeightRandom> loadBalancerFactoryFunc = (serviceProvider, Route, serviceDiscoveryProvider) => new WeightRandom(serviceDiscoveryProvider.Get);
public void ConfigureServices(IServiceCollection services)
{
//services.AddOcelot().AddNacosDiscovery();
services.AddOcelot(Configuration)
.AddNacosDiscovery()
.AddCustomLoadBalancer(loadBalancerFactoryFunc);
//services.AddOcelot().add();
services.AddNacosAspNet(Configuration, "nacos");
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
//}
//app.UseRouting();
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapGet("/", async context =>
// {
// await context.Response.WriteAsync("Hello World!");
// });
//});
app.UseOcelot().Wait();
}
......
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Ocelot.LoadBalancer.LoadBalancers;
using Ocelot.Responses;
using Ocelot.Values;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using Ocelot.DownstreamRouteFinder.Finder;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiGatewayDemo
namespace ApiGateway
{
/// <summary>
/// 自定义负载均衡策略
/// 自定 义负载均衡策略
/// </summary>
public class CustomerBalancer : ILoadBalancer
public class WeightRandom : ILoadBalancer
{
private readonly Func<Task<List<Service>>> _services;
private readonly IConfiguration _configuration;
private readonly object _lock = new object();
private readonly Func<Task<List<Service>>> _services;
private int _last;
public CustomerBalancer(Func<Task<List<Service>>> services)
public WeightRandom(Func<Task<List<Service>>> services)
{
_services = services;
}
public async Task<Response<ServiceHostAndPort>> Lease(HttpContext httpContext)
{
var services = await _services();
//var config = _configuration["appName"];
var services = await
_services();
if (services == null || services.Count == 0)
if (services == null ||
services.Count == 0)
{
return null;
}
......@@ -63,7 +67,6 @@ namespace ApiGatewayDemo
public void Release(ServiceHostAndPort hostAndPort)
{
}
}
}
}
\ No newline at end of file
{
"Nacos": {
"Listeners": [
{
"Optional": false,
"DataId": "ApiGateway",
"Group": "DEFAULT_GROUP"
}
],
"Namespace": "8e6c6559-3b86-4dfa-b817-ad38da91ca37", // Please set the value of Namespace ID !!!!!!!!: null,
"ServerAddresses": [ "http://192.168.3.188:3993" ],
"UserName": "nacos",
"Password": "nacos",
//"AccessKey": "",
//"SecretKey": "",
"ConfigUseRpc": false,
"NamingUseRpc": false
}
//"Kestrel": {
// "Endpoints": {
// "Https": {
// "Url": "https://*:9601"
// },
// "Http": {
// "Url": "http://*:9600"
// }
// }
//}
}
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Debug"
throwExceptions="false"
internalLogFile="internal-nlog.txt">
<targets>
<target xsi:type="File" name="file" fileName="Nlogs/all/nlog-all-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="Debug" fileName="Nlogs/Debug/nlog-Debug-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="Error" fileName="Nlogs/Error/nlog-Error-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="Information" fileName="Nlogs/Information/nlog-Information-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="Null" name="blackhole" />
</targets>
<rules>
<!--<logger name="*" minlevel="Trace" writeTo="file" />-->
<!--<logger name="*" minlevel="Information" maxlevel="Information" writeTo="Information" />-->
<logger name="APIGateway.*" minlevel="Debug" maxlevel="Debug" writeTo="Debug" />
<logger name="*" minlevel="Error" maxlevel="Error" writeTo="Error" />
<!--日志级别:Trace -》Debug-》 Information -》Warning-》 Error-》 Critical-->
<!--排除系统日志-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" />
<!--<logger name="Nacos.*" minlevel="Trace" maxlevel="Information" writeTo="blackhole" final="true"/>-->
</rules>
</nlog>
\ No newline at end of file
......@@ -14,10 +14,9 @@ namespace Ocelot.Provider.Nacos
public class Nacos : IServiceDiscoveryProvider
{
private readonly INacosNamingService _client;
private readonly string _serviceName;
private readonly string _groupName;
private readonly List<string> _clusters;
private readonly string _groupName;
private readonly string _serviceName;
public Nacos(string serviceName, INacosNamingService client, IOptions<NacosAspNetOptions> options)
{
_serviceName = serviceName;
......
......@@ -13,6 +13,7 @@
<ItemGroup>
<PackageReference Include="nacos-sdk-csharp" Version="1.3.4" />
<PackageReference Include="nacos-sdk-csharp.Extensions.Configuration" Version="1.3.4" />
<PackageReference Include="Ocelot" Version="18.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0" />
<PackageReference Include="EasyCaching.InMemory" Version="1.7.0" />
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论