Skip to content

Commit

Permalink
Merge pull request #315 from imiyu/master
Browse files Browse the repository at this point in the history
格式化代码,增加注释
  • Loading branch information
fanliang11 authored Jun 29, 2019
2 parents 4b29dbc + 10404df commit 378d0a8
Show file tree
Hide file tree
Showing 14 changed files with 156 additions and 116 deletions.
3 changes: 3 additions & 0 deletions src/Surging.Core/Surging.Core.CPlatform/AppConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ public class AppConfig

public static IConfigurationRoot Configuration { get; internal set; }

/// <summary>
/// 负载均衡模式
/// </summary>
public static AddressSelectorMode LoadBalanceMode
{
get
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ public static IServiceBuilder RegisterServiceBus
services.RegisterAssemblyTypes(assembly)
.Where(t => typeof(IIntegrationEventHandler).GetTypeInfo().IsAssignableFrom(t)).AsImplementedInterfaces().SingleInstance();
services.RegisterAssemblyTypes(assembly)
.Where(t => typeof(IIntegrationEventHandler).IsAssignableFrom(t)).SingleInstance();
.Where(t => typeof(IIntegrationEventHandler).IsAssignableFrom(t)).SingleInstance();
}
return builder;
}
Expand All @@ -562,8 +562,7 @@ public static IServiceBuilder RegisterServiceBus
/// </summary>
/// <param name="builder">IOC容器</param>
/// <returns>返回注册模块信息</returns>
public static IServiceBuilder RegisterRepositories
(this IServiceBuilder builder, params string[] virtualPaths)
public static IServiceBuilder RegisterRepositories(this IServiceBuilder builder, params string[] virtualPaths)
{
var services = builder.Services;
var referenceAssemblies = GetAssemblies(virtualPaths);
Expand All @@ -576,8 +575,7 @@ public static IServiceBuilder RegisterRepositories
return builder;
}

public static IServiceBuilder RegisterModules(
this IServiceBuilder builder, params string[] virtualPaths)
public static IServiceBuilder RegisterModules(this IServiceBuilder builder, params string[] virtualPaths)
{
var services = builder.Services;
var referenceAssemblies = GetAssemblies(virtualPaths);
Expand All @@ -600,7 +598,7 @@ public static IServiceBuilder RegisterModules(
});
}
builder.Services.Register(provider => new ModuleProvider(
_modules,virtualPaths, provider.Resolve<ILogger<ModuleProvider>>(), provider.Resolve<CPlatformContainer>()
_modules, virtualPaths, provider.Resolve<ILogger<ModuleProvider>>(), provider.Resolve<CPlatformContainer>()
)).As<IModuleProvider>().SingleInstance();
return builder;
}
Expand Down Expand Up @@ -721,7 +719,7 @@ private static List<AbstractModule> GetAbstractModules(Assembly assembly)

private static string[] GetFilterAssemblies(string[] assemblyNames)
{
var notRelatedFile = AppConfig.ServerOptions.NotRelatedAssemblyFiles;
var notRelatedFile = AppConfig.ServerOptions.NotRelatedAssemblyFiles;
var relatedFile = AppConfig.ServerOptions.RelatedAssemblyFiles;
var pattern = string.Format("^Microsoft.\\w*|^System.\\w*|^DotNetty.\\w*|^runtime.\\w*|^ZooKeeperNetEx\\w*|^StackExchange.Redis\\w*|^Consul\\w*|^Newtonsoft.Json.\\w*|^Autofac.\\w*{0}",
string.IsNullOrEmpty(notRelatedFile) ? "" : $"|{notRelatedFile}");
Expand All @@ -738,7 +736,7 @@ private static string[] GetFilterAssemblies(string[] assemblyNames)
return
assemblyNames.Where(
name => !notRelatedRegex.IsMatch(name)).ToArray();
}
}
}

private static List<string> GetAllAssemblyFiles(string parentDir)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,26 @@

namespace Surging.Core.CPlatform.Runtime.Client.Address.Resolvers.Implementation.Selectors.Implementation
{
/// <summary>
/// 负载均衡模式
/// </summary>
public enum AddressSelectorMode
{
/// <summary>
/// Hash算法
/// </summary>
HashAlgorithm,
/// <summary>
/// 轮训
/// </summary>
Polling,
/// <summary>
/// 随机
/// </summary>
Random,
/// <summary>
/// 压力最小优先
/// </summary>
FairPolling,
}
}
2 changes: 0 additions & 2 deletions src/Surging.Core/Surging.Core.CPlatform/ServiceDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ public static string GroupName(this ServiceDescriptor descriptor)
public static ServiceDescriptor GroupName(this ServiceDescriptor descriptor, string groupName)
{
descriptor.Metadatas["GroupName"] = groupName;

return descriptor;
}

Expand Down Expand Up @@ -198,7 +197,6 @@ public ServiceDescriptor()
/// </summary>
public string RoutePath { get; set; }


/// <summary>
/// 元数据。
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@

using Autofac;
using Autofac;
using Surging.Core.CPlatform.Support;
using System.Linq;
using Surging.Core.CPlatform.Routing;
Expand Down Expand Up @@ -33,10 +32,10 @@ public static IServiceHostBuilder UseServer(this IServiceHostBuilder hostBuilder
BuildServiceEngine(mapper);
await mapper.Resolve<IServiceCommandManager>().SetServiceCommandsAsync();
string serviceToken = mapper.Resolve<IServiceTokenGenerator>().GeneratorToken(token);
int _port = AppConfig.ServerOptions.Port= AppConfig.ServerOptions.Port == 0 ? port : AppConfig.ServerOptions.Port;
int _port = AppConfig.ServerOptions.Port = AppConfig.ServerOptions.Port == 0 ? port : AppConfig.ServerOptions.Port;
string _ip = AppConfig.ServerOptions.Ip = AppConfig.ServerOptions.Ip ?? ip;
_port = AppConfig.ServerOptions.Port = AppConfig.ServerOptions.IpEndpoint?.Port ?? _port;
_ip = AppConfig.ServerOptions.Ip =AppConfig.ServerOptions.IpEndpoint?.Address.ToString() ?? _ip;
_ip = AppConfig.ServerOptions.Ip = AppConfig.ServerOptions.IpEndpoint?.Address.ToString() ?? _ip;
_ip = NetUtils.GetHostAddress(_ip);
await ConfigureRoute(mapper, serviceToken);
Expand All @@ -56,7 +55,7 @@ public static IServiceHostBuilder UseServer(this IServiceHostBuilder hostBuilder
var serverOptions = new SurgingServerOptions();
options.Invoke(serverOptions);
AppConfig.ServerOptions = serverOptions;
return hostBuilder.UseServer(serverOptions.Ip,serverOptions.Port,serverOptions.Token);
return hostBuilder.UseServer(serverOptions.Ip, serverOptions.Port, serverOptions.Token);
}

public static IServiceHostBuilder UseClient(this IServiceHostBuilder hostBuilder)
Expand All @@ -70,9 +69,9 @@ public static IServiceHostBuilder UseClient(this IServiceHostBuilder hostBuilder
return new ServiceSubscriber
{
Address = new[] { new IpAddressModel {
Ip = Dns.GetHostEntry(Dns.GetHostName())
.AddressList.FirstOrDefault<IPAddress>
(a => a.AddressFamily.ToString().Equals("InterNetwork")).ToString() } },
Ip = Dns.GetHostEntry(Dns.GetHostName())
.AddressList.FirstOrDefault<IPAddress>
(a => a.AddressFamily.ToString().Equals("InterNetwork")).ToString() } },
ServiceDescriptor = i.Descriptor
};
}).ToList();
Expand All @@ -88,14 +87,14 @@ public static void BuildServiceEngine(IContainer container)
var builder = new ContainerBuilder();

container.Resolve<IServiceEngineBuilder>().Build(builder);
var configBuilder= container.Resolve<IConfigurationBuilder>();
var configBuilder = container.Resolve<IConfigurationBuilder>();
var appSettingPath = Path.Combine(AppConfig.ServerOptions.RootPath, "appsettings.json");
configBuilder.AddCPlatformFile("${appsettingspath}|"+ appSettingPath, optional: false, reloadOnChange: true);
configBuilder.AddCPlatformFile("${appsettingspath}|" + appSettingPath, optional: false, reloadOnChange: true);
builder.Update(container);
}
}

public static async Task ConfigureRoute(IContainer mapper,string serviceToken)
public static async Task ConfigureRoute(IContainer mapper, string serviceToken)
{
if (AppConfig.ServerOptions.Protocol == CommunicationProtocol.Tcp ||
AppConfig.ServerOptions.Protocol == CommunicationProtocol.None)
Expand All @@ -106,9 +105,9 @@ public static async Task ConfigureRoute(IContainer mapper,string serviceToken)
async () => await routeProvider.RegisterRoutes(
Math.Round(Convert.ToDecimal(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds), 2, MidpointRounding.AwayFromZero)));
else
await routeProvider.RegisterRoutes(0);
await routeProvider.RegisterRoutes(0);
}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class BreakeRemoteInvokeService : IBreakeRemoteInvokeService
private readonly ILogger<BreakeRemoteInvokeService> _logger;
private readonly ConcurrentDictionary<string, ServiceInvokeListenInfo> _serviceInvokeListenInfo = new ConcurrentDictionary<string, ServiceInvokeListenInfo>();
private readonly IHashAlgorithm _hashAlgorithm;
private readonly IEnumerable<IExceptionFilter> exceptionFilters=new List<IExceptionFilter>();
private readonly IEnumerable<IExceptionFilter> exceptionFilters = new List<IExceptionFilter>();

public BreakeRemoteInvokeService(IHashAlgorithm hashAlgorithm, IServiceCommandProvider commandProvider, ILogger<BreakeRemoteInvokeService> logger,
IRemoteInvokeService remoteInvokeService,
Expand All @@ -35,23 +35,26 @@ public BreakeRemoteInvokeService(IHashAlgorithm hashAlgorithm, IServiceCommandPr
_logger = logger;
_hashAlgorithm = hashAlgorithm;
if (serviceProvider.Current.IsRegistered<IExceptionFilter>())
exceptionFilters= serviceProvider.GetInstances<IEnumerable<IExceptionFilter>>();
exceptionFilters = serviceProvider.GetInstances<IEnumerable<IExceptionFilter>>();
}

public async Task<RemoteInvokeResultMessage> InvokeAsync(IDictionary<string, object> parameters, string serviceId, string serviceKey, bool decodeJOject)
{
var serviceInvokeInfos = _serviceInvokeListenInfo.GetOrAdd(serviceId,
new ServiceInvokeListenInfo() { FirstInvokeTime=DateTime.Now,
FinalRemoteInvokeTime =DateTime.Now });
var vt = _commandProvider.GetCommand(serviceId);
new ServiceInvokeListenInfo()
{
FirstInvokeTime = DateTime.Now,
FinalRemoteInvokeTime = DateTime.Now
});
var vt = _commandProvider.GetCommand(serviceId);
var command = vt.IsCompletedSuccessfully ? vt.Result : await vt;
var intervalSeconds = (DateTime.Now - serviceInvokeInfos.FinalRemoteInvokeTime).TotalSeconds;
bool reachConcurrentRequest() => serviceInvokeInfos.ConcurrentRequests > command.MaxConcurrentRequests;
bool reachRequestVolumeThreshold() => intervalSeconds <= 10
&& serviceInvokeInfos.SinceFaultRemoteServiceRequests > command.BreakerRequestVolumeThreshold;
bool reachErrorThresholdPercentage() =>
(double)serviceInvokeInfos.FaultRemoteServiceRequests / (double)(serviceInvokeInfos.RemoteServiceRequests ?? 1) * 100 > command.BreakeErrorThresholdPercentage;
var item = GetHashItem(command,parameters);
var item = GetHashItem(command, parameters);
if (command.BreakerForceClosed)
{
_serviceInvokeListenInfo.AddOrUpdate(serviceId, new ServiceInvokeListenInfo(), (k, v) => { v.LocalServiceRequests++; return v; });
Expand All @@ -78,7 +81,7 @@ bool reachErrorThresholdPercentage() =>
}
}

private async Task<RemoteInvokeResultMessage> MonitorRemoteInvokeAsync(IDictionary<string, object> parameters, string serviceId, string serviceKey, bool decodeJOject, int requestTimeout,string item)
private async Task<RemoteInvokeResultMessage> MonitorRemoteInvokeAsync(IDictionary<string, object> parameters, string serviceId, string serviceKey, bool decodeJOject, int requestTimeout, string item)
{
CancellationTokenSource source = new CancellationTokenSource();
var token = source.Token;
Expand All @@ -101,7 +104,7 @@ private async Task<RemoteInvokeResultMessage> MonitorRemoteInvokeAsync(IDictiona
});
var message = await _remoteInvokeService.InvokeAsync(new RemoteInvokeContext
{
Item=item ,
Item = item,
InvokeMessage = invokeMessage
}, requestTimeout);
_serviceInvokeListenInfo.AddOrUpdate(serviceId, new ServiceInvokeListenInfo(), (k, v) =>
Expand All @@ -111,7 +114,7 @@ private async Task<RemoteInvokeResultMessage> MonitorRemoteInvokeAsync(IDictiona
});
return message;
}
catch(Exception ex)
catch (Exception ex)
{
_serviceInvokeListenInfo.AddOrUpdate(serviceId, new ServiceInvokeListenInfo(), (k, v) =>
{
Expand Down Expand Up @@ -141,10 +144,10 @@ await filter.ExecuteExceptionFilterAsync(new RpcActionExecutedContext
private string GetHashItem(ServiceCommand command, IDictionary<string, object> parameters)
{
string result = "";
if(command.ShuntStrategy==AddressSelectorMode.HashAlgorithm)
if (command.ShuntStrategy == AddressSelectorMode.HashAlgorithm)
{
var parameter = parameters.Values.FirstOrDefault();
result= parameter?.ToString();
result = parameter?.ToString();
}
return result;
}
Expand Down
16 changes: 11 additions & 5 deletions src/Surging.Core/Surging.Core.CPlatform/Support/ServiceCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,13 @@ public ServiceCommand()
FallBackName = AppConfig.ServerOptions.FallBackName;
}
}
/// <summary>
/// 故障转移次数
/// </summary>
public int FailoverCluster { get; set; } = 3;
/// <summary>
/// 是否强制开启熔断
/// </summary>
public bool CircuitBreakerForceOpen { get; set; }
/// <summary>
/// 容错策略
Expand All @@ -45,7 +51,6 @@ public ServiceCommand()
/// </summary>
public string Injection { get; set; } = "return null";


/// <summary>
/// IFallbackInvoker 实例名称
/// </summary>
Expand All @@ -55,9 +60,10 @@ public ServiceCommand()
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public AddressSelectorMode ShuntStrategy { get; set; } = AddressSelectorMode.Polling;

/// <summary>
/// 注入命名空间
/// </summary>
public string[] InjectionNamespaces { get; set; }

/// <summary>
/// 错误率达到多少开启熔断保护
/// </summary>
Expand All @@ -67,12 +73,12 @@ public ServiceCommand()
/// </summary>
public int BreakeSleepWindowInMilliseconds { get; set; } = 60000;
/// <summary>
/// 是否强制关闭熔断
/// 是否强制关闭熔断
/// </summary>
public bool BreakerForceClosed { get; set; }

/// <summary>
/// 10秒钟内至少多少请求失败,熔断器才发挥起作用
/// 10秒钟内至少多少请求失败,熔断器才发挥起作用
/// </summary>
public int BreakerRequestVolumeThreshold { get; set; } = 20;

Expand Down
18 changes: 15 additions & 3 deletions src/Surging.Core/Surging.Core.CPlatform/Support/StrategyType.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
namespace Surging.Core.CPlatform.Support
{
/// <summary>
/// 容错策略
/// </summary>
public enum StrategyType
{
Failover=0,
Injection=1,
FallBack=2,
/// <summary>
/// 故障转移策略、失败切换远程服务机制
/// </summary>
Failover = 0,
/// <summary>
/// 脚本注入策略、失败执行注入脚本
/// </summary>
Injection = 1,
/// <summary>
/// 回退策略、失败时调用通过FallBackName指定的接口
/// </summary>
FallBack = 2,
}
}
12 changes: 6 additions & 6 deletions src/Surging.Core/Surging.Core.CPlatform/Utilities/NetUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@

namespace Surging.Core.CPlatform.Utilities
{
public class NetUtils
public class NetUtils
{
public const string LOCALHOST = "127.0.0.1";
public const string ANYHOST = "0.0.0.0";
private const int MIN_PORT = 0;
private const int MAX_PORT = 65535;
private const string LOCAL_IP_PATTERN = "127(\\.\\d{1,3}){3}$";
private const string IP_PATTERN = "\\d{1,3}(\\.\\d{1,3}){3,5}$";
private static AddressModel _host=null;
private static AddressModel _host = null;

public static bool IsInvalidPort(int port)
{
Expand All @@ -36,7 +36,7 @@ public static bool IsAnyHost(String host)
private static bool IsValidAddress(string address)
{
return (address != null
&& !ANYHOST.Equals(address)
&& !ANYHOST.Equals(address)
&& address.IsMatch(IP_PATTERN));
}

Expand Down Expand Up @@ -74,7 +74,7 @@ public static string GetAnyHostAddress()
public static string GetHostAddress(string hostAddress)
{
var result = hostAddress;
if((!IsValidAddress(hostAddress) && !IsLocalHost(hostAddress)) || IsAnyHost(hostAddress))
if ((!IsValidAddress(hostAddress) && !IsLocalHost(hostAddress)) || IsAnyHost(hostAddress))
{
result = GetAnyHostAddress();
}
Expand All @@ -88,11 +88,11 @@ public static AddressModel GetHostAddress()
var ports = AppConfig.ServerOptions.Ports;
string address = GetHostAddress(AppConfig.ServerOptions.Ip);
int port = AppConfig.ServerOptions.Port;
var mappingIp = AppConfig.ServerOptions.MappingIP ?? address;
var mappingIp = AppConfig.ServerOptions.MappingIP ?? address;
var mappingPort = AppConfig.ServerOptions.MappingPort;
if (mappingPort == 0)
mappingPort = port;
_host= new IpAddressModel
_host = new IpAddressModel
{
HttpPort = ports.HttpPort,
Ip = mappingIp,
Expand Down
Loading

0 comments on commit 378d0a8

Please sign in to comment.