//the method check the service discovery parameter register ipaddress to generate service agent
        //those service agents will deregister when the app stop
        public static IApplicationBuilder UseConsulRegisterService(this IApplicationBuilder app, IConfiguration configuration)
        {
            ConsulServiceDiscoveryOption serviceDiscoveryOption = new ConsulServiceDiscoveryOption();

            configuration.GetSection("ServiceDiscovery").Bind(serviceDiscoveryOption);
            app.UseConsulRegisterService(serviceDiscoveryOption);
            return(app);
        }
        public static IServiceCollection AddNanoFabricConsul(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddOptions();
            services.Configure <ConsulServiceDiscoveryOption>(configuration.GetSection("ServiceDiscovery"));
            services.RegisterConsulClient();
            services.RegisterDnsLookup();
            ConsulServiceDiscoveryOption serviceDiscoveryOption = new ConsulServiceDiscoveryOption();

            configuration.GetSection("ServiceDiscovery").Bind(serviceDiscoveryOption);
            services.AddNanoFabric(() => new ConsulRegistryHost(serviceDiscoveryOption.Consul));
            return(services);
        }
Exemplo n.º 3
0
        /// <summary>
        /// 服务发现
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configAction"></param>
        /// <returns></returns>
        public static IServiceCollection AddServiceDiscoveryConsul(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure <ConsulServiceDiscoveryOption>(configuration.GetSection("ServiceDiscovery"));

            services.AddSingleton <ILoadBalancerFactory, LoadBalancerFactory>();
            services.AddSingleton <ILoadBalancerHouse, LoadBalancerHouse>();

            ConsulServiceDiscoveryOption serviceDiscoveryOption = new ConsulServiceDiscoveryOption();

            configuration.GetSection("ServiceDiscovery").Bind(serviceDiscoveryOption);

            services.AddSingleton <IServiceDiscovery>(p => new ConsulServiceDiscovery(serviceDiscoveryOption.Consul));

            return(services);
        }
Exemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();


            IConfiguration config = new ConfigurationBuilder()
                                    .Add(new JsonConfigurationSource {
                Path = "config/servers.json", ReloadOnChange = true
            })
                                    .Build();

            var result = config.GetSection("ServiceDiscovery")["ServiceName"];

            //services.Configure<ConsulHostConfiguration>()

            //configuration.GetSection("ServiceDiscovery: Consul")
            //services.Configure<ConsulHostConfiguration>(.GetSection("ServiceDiscovery:Consul"));

            //services.AddHorizonConsul(new ConfigurationBuilder().AddJsonFile("config\\servers.json").Build());


            services.AddHorizonConsul(Configuration);


            ConsulServiceDiscoveryOption host = new ConsulServiceDiscoveryOption();

            config.GetSection("ServiceDiscovery").Bind(host);

            var serviecname = host.ServiceName;
            var s           = host.Consul.HttpEndpoint;

            Console.WriteLine($"servicename:{serviecname}");
            Console.WriteLine($"url:{s}");

            services.AddCors(options => options.AddPolicy
                             (
                                 "HorizonCors",
                                 p => p.SetIsOriginAllowedToAllowWildcardSubdomains()
                                 .WithOrigins("https://*.cnblogs.com", "http://*.cnblogs.com")
                                 .AllowAnyMethod().AllowAnyHeader()
                             )
                             );
        }
Exemplo n.º 5
0
        public static IServiceCollection AddHorizonConsul(this IServiceCollection services, IConfiguration configuration)
        {
            //services.Configure<ConsulServiceDiscoveryOption>(configuration.GetSection("ServiceDiscovery"));

            services.AddSingleton <IRegistryHost, ConsulProxy>();

            Console.WriteLine("consulproxy .....regsited");


            services.RegisterDnsLookup();

            ConsulServiceDiscoveryOption serviceDiscoveryOption = new ConsulServiceDiscoveryOption();

            configuration.GetSection("ServiceDiscovery").Bind(serviceDiscoveryOption);

            services.AddConsul(() => new ConsulProxy(serviceDiscoveryOption.Consul));

            return(services);
            //configuration.GetSection("ServiceDiscovery: Consul");
        }
        //the method check the service discovery parameter register ipaddress to generate service agent
        //those service agents will deregister when the app stop
        public static IApplicationBuilder UseConsulRegisterService(this IApplicationBuilder app, ConsulServiceDiscoveryOption serviceDiscoveryOption)
        {
            var applicationLifetime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>() ??
                                      throw new ArgumentException("Missing Dependency", nameof(IApplicationLifetime));

            if (serviceDiscoveryOption.Consul == null)
            {
                throw new ArgumentException("Missing Dependency", nameof(serviceDiscoveryOption.Consul));
            }
            var consul = app.ApplicationServices.GetRequiredService <IConsulClient>() ?? throw new ArgumentException("Missing dependency", nameof(IConsulClient));

            //create logger to record the important information
            var loggerFactory = app.ApplicationServices.GetRequiredService <ILoggerFactory>();
            var logger        = loggerFactory.CreateLogger("NanoFabricServiceBuilder");

            if (string.IsNullOrEmpty(serviceDiscoveryOption.ServiceName))
            {
                throw new ArgumentException("service name must be configure", nameof(serviceDiscoveryOption.ServiceName));
            }
            IEnumerable <Uri> addresses = null;

            if (serviceDiscoveryOption.Endpoints != null && serviceDiscoveryOption.Endpoints.Length > 0)
            {
                logger.LogInformation($"Using {serviceDiscoveryOption.Endpoints.Length} configured endpoints for service registration");
                addresses = serviceDiscoveryOption.Endpoints.Select(p => new Uri(p));
            }
            else
            {
                logger.LogInformation($"Trying to use server.Features to figure out the service endpoint for registration.");
                var features = app.Properties["server.Features"] as FeatureCollection;
                addresses = features.Get <IServerAddressesFeature>().Addresses.Select(p => new Uri(p)).ToArray();
            }

            foreach (var address in addresses)
            {
                var serviceID = GetServiceId(serviceDiscoveryOption.ServiceName, address);
                logger.LogInformation($"Registering service {serviceID} for address {address}.");
                Uri healthCheck = null;
                if (!string.IsNullOrEmpty(serviceDiscoveryOption.HealthCheckTemplate))
                {
                    healthCheck = new Uri(address, serviceDiscoveryOption.HealthCheckTemplate);
                    logger.LogInformation($"Adding healthcheck for {serviceID},checking {healthCheck}");
                }
                var registryInformation = app.AddTenant(serviceDiscoveryOption.ServiceName, serviceDiscoveryOption.Version, address, healthCheckUri: healthCheck, tags: new[] { $"urlprefix-/{serviceDiscoveryOption.ServiceName}" });
                logger.LogInformation("Registering additional health check");
                // register service & health check cleanup
                applicationLifetime.ApplicationStopping.Register(() =>
                {
                    logger.LogInformation("Removing tenant & additional health check");
                    app.RemoveTenant(registryInformation.Id);
                });
            }
            return(app);
        }
Exemplo n.º 7
0
        public static IApplicationBuilder UseConsulRegisterService(this IApplicationBuilder app, ConsulServiceDiscoveryOption serviceDiscoveryOption)
        {
            var applicationLifetime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>() ??
                                      throw new ArgumentException("Missing Dependency", nameof(IApplicationLifetime));

            if (serviceDiscoveryOption.Consul == null)
            {
                throw new ArgumentException("Missing Dependency", nameof(serviceDiscoveryOption.Consul));
            }



            if (string.IsNullOrEmpty(serviceDiscoveryOption.ServiceName))
            {
                throw new ArgumentException("service name must be configure", nameof(serviceDiscoveryOption.ServiceName));
            }

            IEnumerable <Uri> addresses = null;

            var dockerip = "";

            if (serviceDiscoveryOption.Endpoints != null && serviceDiscoveryOption.Endpoints.Length > 0)
            {
                Log.Information($"Using {serviceDiscoveryOption.Endpoints.Length} configured endpoints for service registration");
                addresses = serviceDiscoveryOption.Endpoints.Select(p => new Uri(p));
            }
            else
            {
                if (!DockerHelper.IsRunningInDocker)
                {
                    Log.Information($"Trying to use server.Features to figure out the service endpoint for registration.");
                    var features = app.Properties["server.Features"] as FeatureCollection;
                    addresses = features.Get <IServerAddressesFeature>().Addresses.Select(p => new Uri(p)).ToArray();
                    Log.Information($"this services ip is : {addresses.First().DnsSafeHost}");
                }
                else
                {
                    Log.Information($"Triying to use docker to figure out the service endpoint for registration.");

                    Log.Information($"The Docker IP is {DockerHelper.ContainerAddress}....setup 1.");
                    if (DockerHelper.ContainerAddress != null)
                    {
                        Log.Information($"The Docker IP is {DockerHelper.ContainerAddress}....setup 2.");
                        dockerip = DockerHelper.ContainerAddress;
                        Log.Information($"This services {DockerHelper.ContainerAddress} on docker.");
                    }
                    else
                    {
                        throw new ArgumentException("can not get docker services ip");
                    }
                }
            }

            //run in docker
            if (DockerHelper.IsRunningInDocker)
            {
                var port      = 5022;
                var address   = new Uri("http://" + dockerip + ":" + port);
                var serviceID = GetServiceId(serviceDiscoveryOption.ServiceName, address);
                Log.Information($"Registering service {serviceID} for address {dockerip}.");
                Uri    healthCheck = null;
                string url         = "";
                if (!string.IsNullOrEmpty(serviceDiscoveryOption.HealthCheckTemplate))
                {
                    url = "http://" + dockerip + ":" + serviceDiscoveryOption.HealthCheckTemplate;


                    healthCheck = new Uri(url);
                    //healthCheck = new Uri(address, serviceDiscoveryOption.HealthCheckTemplate);
                    Log.Information($"Adding healthcheck for {serviceID},checking {healthCheck}");
                }
                var registryInformation = app.AddTenant(serviceDiscoveryOption.ServiceName, serviceDiscoveryOption.Version, address, healthCheckUri: healthCheck, tags: new[] { $"urlprefix-/{serviceDiscoveryOption.ServiceName}" });
                Log.Information($"Registering sevices {serviceDiscoveryOption.ServiceName} and {healthCheck} on {address}...........");

                // register service & health check cleanup
                applicationLifetime.ApplicationStopping.Register(() =>
                {
                    Log.Information("Removing tenant & additional health check");
                    app.RemoveTenant(registryInformation.Id);
                });
                return(app);
            }



            //run in os
            foreach (var address in addresses)
            {
                var serviceID = GetServiceId(serviceDiscoveryOption.ServiceName, address);
                Log.Information($"Registering service {serviceID} for address {address}.");
                Uri    healthCheck = null;
                string url         = "";
                if (!string.IsNullOrEmpty(serviceDiscoveryOption.HealthCheckTemplate))
                {
                    url = "http://" + address.DnsSafeHost + ":" + serviceDiscoveryOption.HealthCheckTemplate;


                    healthCheck = new Uri(url);
                    //healthCheck = new Uri(address, serviceDiscoveryOption.HealthCheckTemplate);
                    Log.Information($"Adding healthcheck for {serviceID},checking {healthCheck}");
                }
                var registryInformation = app.AddTenant(serviceDiscoveryOption.ServiceName, serviceDiscoveryOption.Version, address, healthCheckUri: healthCheck, tags: new[] { $"urlprefix-/{serviceDiscoveryOption.ServiceName}" });
                Log.Information($"Registering sevices {serviceDiscoveryOption.ServiceName} and {healthCheck} on {address}...........");

                // register service & health check cleanup
                applicationLifetime.ApplicationStopping.Register(() =>
                {
                    Log.Information("Removing tenant & additional health check");
                    app.RemoveTenant(registryInformation.Id);
                });
            }
            return(app);
        }
        //the method check the service discovery parameter register ipaddress to generate service agent
        //those service agents will deregister when the app stop
        public static IApplicationBuilder UseConsulRegisterService(this IApplicationBuilder app, ConsulServiceDiscoveryOption serviceDiscoveryOption)
        {
            var applicationLifetime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>() ??
                                      throw new ArgumentException("Missing Dependency", nameof(IApplicationLifetime));

            if (serviceDiscoveryOption.Consul == null)
            {
                throw new ArgumentException("Missing Dependency", nameof(serviceDiscoveryOption.Consul));
            }

            if (string.IsNullOrEmpty(serviceDiscoveryOption.ServiceName))
            {
                throw new ArgumentException("service name must be configure", nameof(serviceDiscoveryOption.ServiceName));
            }

            IEnumerable <Uri> addresses = null;

            if (serviceDiscoveryOption.Endpoints != null && serviceDiscoveryOption.Endpoints.Length > 0)
            {
                addresses = serviceDiscoveryOption.Endpoints.Select(p => new Uri(p));
            }
            else
            {
                var features = app.Properties["server.Features"] as FeatureCollection;
                addresses = features.Get <IServerAddressesFeature>().Addresses.Select(p => new Uri(p)).ToArray();
            }

            var serviceChecks = new List <AgentServiceCheck>();

            foreach (var address in addresses)
            {
                var serviceID = GetServiceId(serviceDiscoveryOption.ServiceName, address);

                Uri healthCheck = null;
                if (!string.IsNullOrEmpty(serviceDiscoveryOption.HealthCheckTemplate))
                {
                    healthCheck = new Uri(address, serviceDiscoveryOption.HealthCheckTemplate);
                }
                var registryInformation = app.AddTenant(serviceDiscoveryOption.ServiceName, serviceDiscoveryOption.Version, address, healthCheckUri: healthCheck, tags: new[] { $"urlprefix-/{serviceDiscoveryOption.ServiceName}" });

                applicationLifetime.ApplicationStopping.Register(() =>
                {
                    app.RemoveTenant(registryInformation.Id);
                });
            }
            return(app);
        }