/// <summary> /// 服务注册 /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseGrpcRegister(this IApplicationBuilder app, Action <GrpcOptions> grpcOptionBuilder = null) { var grpcOptions = new GrpcOptions(); grpcOptionBuilder?.Invoke(grpcOptions); var serverAddressFeature = app.ServerFeatures.Get <IServerAddressesFeature>(); if (serverAddressFeature?.Addresses?.Count > 0) { grpcOptions.ListenAddress = serverAddressFeature.Addresses.FirstOrDefault(); } RegisterFactory.WithConsul(grpcOptions); return(app); }
/// <summary> /// 解析配置 /// </summary> /// <param name="configPath"></param> private static ServiceElement ResolveServiceConfiguration(GrpcOptions grpcOptions = null) { var sectionName = Constants.GrpcServerSectionName; var grpcSection = ConfigBuilder.Build <GrpcServerSection>(sectionName, grpcOptions?.ConfigPath); if (grpcSection == null) { throw new ArgumentNullException(sectionName); } var service = grpcSection.Service; if (service == null) { throw new ArgumentNullException($"service"); } if (string.IsNullOrWhiteSpace(service.Name)) { throw new ArgumentNullException("serviceName"); } if (service.Port <= 0) { if (!string.IsNullOrWhiteSpace(grpcOptions.ListenAddress)) { var splits = grpcOptions.ListenAddress?.Split(":"); if (splits?.Length == 3 && int.TryParse(splits[2], out int port)) { service.Port = port; } } if (service.Port <= 0) { throw new ArgumentNullException("servicePort"); } } return(grpcSection.Service); }
/// <summary> /// Consul注册 /// </summary> /// <param name="servicgrpcOptionses">配置</param> /// <param name="whenException">==null => throw</param> public static void WithConsul( GrpcOptions grpcOptions = null, Action <Exception> whenException = null) { try { var serviceElement = ResolveServiceConfiguration(grpcOptions); #region 注册服务 var address = ResolveConsulConfiguration(serviceElement); if (string.IsNullOrWhiteSpace(address)) { return; } serverRegister = new ConsulRegister(address, grpcOptions.GenServiceId); serverRegister.Register(serviceElement, entry => discoveryEntry = entry); #endregion } catch (Exception ex) { RemoveConsul(); InvokeException(ex, whenException); } }