.NET 注册到consul 建立API网关-ocelot

Ocelot   路由  请求聚合  服务发现 认证  鉴权 限流熔断 内置负载均衡器

Consul   自动服务发现    健康检查 如一个存储dns

nginx  单点故障

从单体到分布式到微服务,单体所有数据调用页面显示都在一个项目中;分布式将系统部署在多个服务器;微服务将一些业务作为一个服务开发部署,通过webapi从项目中拆离,服务端通过httpclient调用api,将webapi部署在多个服务器上或docker上,webapi注册到consul。

一.webapi自动注册到consul,健康检查,自动解除等。

1.下载consul

2.cmd在consul.exe的路径下 执行consul agent -dev

3.安装consul组件

Install-Package Consul -Version 0.7.2.6

4.添加健康检查及注册服务。

添加HealthController,简单的方法实现。
using System;
using Microsoft.AspNetCore.Mvc;

namespace coreapi.Controllers
{
    [Produces("application/json")]
    [Route("api/health")]
    public class HealthController:Controller
    {
        [HttpGet]
       
        public IActionResult Get()
        {

            Console.WriteLine("健康检查"+DateTime.Now);
            return Content("OK");
        }

    }
}

startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            
            app.UseMvc();
            //注册consul 
            string ip="127.0.0.1";//要注册的服务地址
            string port="5000";//注册的服务端口
            string serviceName="Values";
           // string serviceId="test123456789";
            using (var ConsulClient =new ConsulClient(ConsulConfig))
            {

                AgentServiceRegistration asr=new AgentServiceRegistration
                {
                    Address =ip,
                    Port=Convert.ToInt32(port),
                    ID=Guid.NewGuid().ToString(),
                    Name=serviceName,
                    Check=new AgentServiceCheck
                    {

                        DeregisterCriticalServiceAfter=TimeSpan.FromSeconds(5),//服务启动多久后注册
                        HTTP="http://127.0.0.1:5000/api/health",
                        Interval=TimeSpan.FromSeconds(10),//健康检查时间间隔
                        Timeout=TimeSpan.FromSeconds(5),
                
                    },

                };
                ConsulClient.Agent.ServiceRegister(asr).Wait();//服务注册
            }
        private void ConsulConfig(ConsulClientConfiguration config)
        {

            config.Address=new Uri("http://127.0.0.1:8500");
            config.Datacenter="dc1";
        }
 

创建业务api,添加ValuesController,serviceName=values,实现一些方法

   
    public class ValuesController : Controller
    {
        
      [Route("api/Values/Getid/{id}")]
        [HttpGet()] 
       
        public string Getid(int id)
        {
            return "hello world, "+id;
        }
}
  启动,在consul中注册。      

 以上是api注册到consul,对服务进行健康检查,如果其中一台服务挂了    在一分钟内   请求还会转发给这台服务器   一分钟后这台服务还是挂的   consul会自动移除这台服务     这时候就可以动态的实现服务的新增。

consul也可以做负载均衡的策略,轮回随机等。

二.ocelot-API网关

将所有API的调用统一接入API网关层,由网关层负责接入和输出。

1.创建webapp项目,命令dotnet new mvc 

2.vscdode工具需要添加解决方案名,然后添加现有的webapp项目

3.在package下添加package,添加ocelot 13.5.2

4.完成后项目中添加ocelot.json文件(分别在5010跑一个webapi,5000也跑一个webapi)

{
    "ReRoutes": [
      {
       
        "UpstreamPathTemplate": "/api/values",//暴露出去的地址
        "UpstreamHttpMethod": [ "Get" ],
   
     
        "DownstreamPathTemplate": "/api/values",//转发的地址
        "DownstreamScheme": "http",
       //资源服务器列表
        "DownstreamHostAndPorts": [
          {
            "host": "localhost",
            "port": 5010
          },
          {
            "host": "localhost",
            "port": 5000
          }
        ],
        
        "LoadBalancerOptions": {
          "Type": "LeastConnection"
        },
        "UseServiceDiscovery": true
      }
    ],
    //负载均衡算法
    "GlobalConfiguration": {
      "BaseUrl": "http://localhost:5002"
    }
  }

在start.cs下配置,增加

services.AddOcelot(),
app.UseOcelot().Wait()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

namespace webapp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddOcelot();
           
        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

                  app.UseOcelot().Wait();
        }
    }
}

在program.cs下配置访问.json文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace webapp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                 .ConfigureAppConfiguration((hostingContext, builder) =>
                     {
                         builder
                         .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                         .AddJsonFile("Ocelot.json");
                     })
                
                .UseUrls("http://127.0.0.1:5002")
                .UseStartup<Startup>()
                .Build();
                
    }
}

启动即可。访问127.0.0.1:5002/api/value访问,实现了负载均衡。

 

这种做法, 如果其中一台服务器挂了, Ocelot没办法知道,还是会转发接口过去,Consul则实现自动服务发现和服务健康监测。

原文地址:https://www.cnblogs.com/yokiblogs/p/13267910.html