Ocelot and Consul achieve load balancing service registration API Gateway

Ocelot is implemented in a .NET Core and open source API Gateway, it is powerful, including: routing, aggregation request, service discovery, authentication, authorization, limiting fuse, and built-in load balancer and Service Fabric, Butterfly Tracing integrated. These functions only require only a simple configuration can be completed

Consul Service Discovery

Ocelot has the support of a simple load function, that is, when there are multiple nodes downstream services, Ocelot able to assume the role of load balancing. But it does not provide health checks, registration service can only be done by manually adding the configuration file inside. This is not flexible enough and there will be a certain degree of risk. This time we can use the service to do the Consul found it the perfect combination with Ocelot.

What is the Consul

Consul is a service grid (TCP / IP between micro-service network calls between the responsible services, current limiting, fuse and monitoring) solution, which is a distributed, highly available system, and are developed using very simple. It provides a full-featured control plane, the main features are: service discovery, health checks, key storage, security service communication, multiple data centers.

Installation Consul: windos environment

https://www.consul.io/downloads.html Download file

Put the D drive

 

 

 

 

 Open powershell command to start the implementation of a development model of Agent:

 

 

 Start Completion: Open localhost: 8500 default port 8500, you can see a visual consul interface, you can see the default service launched a consul

 

Next, netcore by Ocelot build API Gateway Load Balancing service registration

Create a new api1: nuget add a consul dependent

 Add code startup

void the Configure public (App IApplicationBuilder, IHostingEnvironment the env, IApplicationLifetime Lifetime) 
        { 
            IF (env.IsDevelopment ()) 
            { 
                app.UseDeveloperExceptionPage (); 
            } 


            // Register project start method 
            lifetime.ApplicationStarted.Register (the OnStart); 
            // item registration Close method 
            lifetime.ApplicationStarted.Register (OnStopped); 

            app.UseMvc (); 
        } 

        // close when the consul removed 
        Private void OnStopped () 
        { 
            var = new new ConsulClient Client ();  
            // the ID of the consul Removes the current service
            client.Agent.ServiceDeregister ( " SERVICENAME: 93 "); 
        } 
        Private void the OnStart () 
        { 
            var = new new ConsulClient Client (); 
            // check the health 
            var = httpCheck new new AgentServiceCheck () 
            { 
                // After one minute service error will automatically be removed 
                = TimeSpan.FromMinutes DeregisterCriticalServiceAfter (1), 
                // send once every 10 seconds a request to the address below this address is the address of the current API resource 
                Interval = TimeSpan.FromSeconds (10), 
                HTTP = $ "HTTP: // localhost: 93 / HealthCheck " 
            }; 

            var = agentReg new new AgentServiceRegistration () 
            { 
                unique ID // this resources and services 
                = ID "SERVICENAME: 93", 
                the Check = httpCheck,
                Address = "localhsot",
                Name = "servicename",
                Port = 93
            };
            client.Agent.ServiceRegister(agentReg).ConfigureAwait(false);
        }

  Add a health check Interface

 [Route("HealthCheck")]
    [ApiController]
    public class HealthCheckController : ControllerBase
    {
        // GET: api/HealthCheck
        [HttpGet]
        [HttpHead]
        public IActionResult Ping()
        {
            return Ok();
        }

    }

  Modify ValuesController

 [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public string Get()
        {
            return "这是1资源服务器API";
        }
    }

Then copy a api1 to api2 ,, we enable port 92, the details ........

Add items Api.Gateway (Ocelot gateway server) add Ocelot Ocelot package adds Ocelot.Json configuration server port 91

Ocelot,Json

{ 
  "Reroutes": [ 
    { 
      // To expose the address 
      "UpstreamPathTemplate": "/ API / {Controller}", 
      "UpstreamHttpMethod": [ "the Get"], 

      // forwarded to the following address 
      "DownstreamPathTemplate": "/ api / {Controller} ", 
      " DownstreamScheme ":" HTTP ", 
      // resource list server 
      " DownstreamHostAndPorts ": [ 
        { 
          " Host ":" localhost ", 
          " Port ": 92 
        }, 
        { 
          " Host ":" localhost ", 
          " Port ": 93 
        } 
      ],
      // determine the load balancing algorithm 
      "LoadBalancerOptions": { 
        "Type": "leastconnection" 
      },
      "UseServiceDiscovery": to true 
    } 
  ], 
  access to the address that is exposed outside // server address where the Ocelot 
  "GlobalConfiguration": { 
    "BaseUrl": "HTTP: // localhost: 91" 
  } 
}

  Startup modification

      public void ConfigureServices(IServiceCollection services)
        {


            services.AddOcelot();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseOcelot().Wait();
            app.UseMvc();
        }

  Program modifications

 public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                      .ConfigureAppConfiguration((hostingContext, builder) =>
                      {
                          builder
                          .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                          .AddJsonFile("Ocelot.json");
                      })
              .UseUrls("http://+:91")
              .UseStartup<Startup>();
    }

  

Start api3 and api2

 

 

Restart Api.Gateway

执行 http://localhost:91/api/values

 

 Then perform

 

 Here we load balancing algorithm is: LeastConnection

Of course, you can also choose other:

  • RoundRobin - polling, next to
  • LeastConnection - minimum number of connections, whose mission minimal Who
  • NoLoadBalance - Do not load balancing

 

If api1 we turn off, then it will only request to api2, api1 automatic disconnection of service

Guess you like

Origin www.cnblogs.com/liaokui/p/11532115.html