public static IServiceHostServerBuilder UseInServerForDiscovery(this IServiceHostServerBuilder serviceHostBuilder) { serviceHostBuilder.RegisterService(containerBuilder => { containerBuilder.RegisterType <InServerServiceDiscovery>().As <IServiceDiscovery>().SingleInstance(); containerBuilder.RegisterType <InServerServiceDiscovery>().AsSelf().AsImplementedInterfaces().InstancePerDependency(); }); serviceHostBuilder.AddInitializer(async container => { ILogger logger = container.Resolve <ILogger>(); logger.Info($"本地服务器为注册服务器"); while (!container.IsRegistered <IServer>()) { default(SpinWait).SpinOnce(); } IServer server = container.Resolve <IServer>(); IServiceEntryContainer entryContainer = container.Resolve <IServiceEntryContainer>(); // 添加一个获取所有服务路径的服务 entryContainer.AddServices(new[] { typeof(InServerServiceDiscovery) }); List <ServiceRoute> routes = server.GetServiceRoutes(); IServiceDiscovery discovery = container.Resolve <IServiceDiscovery>(); await discovery.ClearAsync(); await discovery.SetRoutesAsync(routes); }); return(serviceHostBuilder); }
public static IServiceHostServerBuilder UseConsulCheckHealth(this IServiceHostServerBuilder serviceHostBuilder, RegisterServer registerServer) { serviceHostBuilder.RegisterService(containerBuilder => { List <NamedParameter> ListNamedParameter = new List <NamedParameter>() { new NamedParameter("registerServer", registerServer), new NamedParameter("address", serviceHostBuilder.Address), }; containerBuilder.RegisterType <ConsulDiscovery>().As <IServiceDiscovery>().As <IHealthCheck>().WithParameters(ListNamedParameter).SingleInstance(); }); serviceHostBuilder.AddInitializer(container => { while (!container.IsRegistered <IServer>()) { //default(SpinWait).SpinOnce(); Thread.Sleep(200); } ILogger logger = container.Resolve <ILogger>(); logger.Info($"[config]use consul for services discovery, consul ip: {registerServer.Ip}:{registerServer.Port}"); IServer server = container.Resolve <IServer>(); List <ServiceRoute> routes = server.GetServiceRoutes(); logger.Debug("running consul found routes count: " + routes.Count); try { IServiceDiscovery discovery = container.Resolve <IServiceDiscovery>(); discovery.ClearAsync().Wait(); discovery.SetRoutesAsync(routes).Wait(); } catch (Exception ex) { logger.Error($"error occurred while connecting with consul, ensure consul is running.\r\n", ex); } }); serviceHostBuilder.AddRunner(container => { IServer server = container.Resolve <IServer>(); IHealthCheck check = container.Resolve <IHealthCheck>(); check.RunAsync(); }); return(serviceHostBuilder); }