02-01 .net core 3.1 使用 Ocelot搭建api网关

网关的理解

API网关是微服务架构中的唯一入口,它提供一个单独且统一的API入口用于访问内部一个或多个API。它可以具有身份验证,监控,负载均衡,缓存,请求分片与管理,静态响应处理等。API网关方式的核心要点是,所有的客户端和消费端都通过统一的网关接入微服务,在网关层处理所有的非业务功能。通常,网关也是提供REST/HTTP的访问API。服务端通过API-GW注册和管理服务。

Ocelot介绍

Ocelot是用.net Core实现的一款开源的网关,Ocelot其实就是一组按照顺序排列的.net core中间件。它接受到请求之后用request builder构建一个HttpRequestMessage对象并发送到下游服务,当下游请求返回到Ocelot管道时再由一个中间件将HttpRequestMessage映射到HttpResponse上返回客户端。

开始实践

1、使用vs2019创建基于.net core 3.1的webApi项目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2、添加一个ApiController.cs,定义路由访问规则(这是我的个人习惯,你也可以使用默认创建的规则)
namespace WebApiGateway
{
    /// <summary>
    /// 路由访问规则
    /// </summary>
    [Route("api/[controller]/[action]")]
    public class ApiController : Controller
    {
    }
}
3、添加一个GatewayApiController.cs,继承上面的ApiController.cs,添加一个action,返回一个结果
namespace WebApiGateway
{
    /// <summary>
    /// api 网关
    /// </summary>
    public class GatewayApiController : ApiController
    {
        [HttpGet]
        public string Get()
        {
            return @"我是api网关!我是微服务架构中的唯一入口,
                    我提供一个单独且统一的API入口用于访问内部一个或多个API。";
        }
    }
}

如图
在这里插入图片描述

4、新添加两个webApi项目,分别命名为FirstApi,SecondApi ,如图

在这里插入图片描述
接下来的操作参考 步骤 1 中创建WebApiGateway项目步骤,但是FirstApi和SecondApi项目不用再安装Ocelot包,最终如图
在这里插入图片描述

注意在本文例子中FirstApi和SecondApi项目的路由规则必须以controller开始,如下

(1) FirstApi项目中的ApiController.cs

namespace FirstApi
{
    /// <summary>
    /// 路由访问规则
    /// </summary>
    [Route("[controller]/[action]")]
    public class ApiController : Controller
    {
    }
}

(2) SecondApi项目中的ApiController.cs

namespace SecondApi
{
    /// <summary>
    /// 路由访问规则
    /// </summary>
    [Route("[controller]/[action]")]
    public class ApiController : Controller
    {
    }
}
5、修改三个项目的Program.cs的CreateHostBuilder方法,设置默认访问端口,分别设置为5000,5001,5002,如
namespace WebApiGateway
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseUrls("http://localhost:5000")   //设置默认访问端口(也可以设置成https)
                    .UseStartup<Startup>();
                });
    }
}

如图
在这里插入图片描述

6、使用nuget程序包管理器安装Ocelot,如图

在这里插入图片描述

7、在WebApiGateway新建一个configuration.json配置文件(在本文例子中如下配置)
{
  //全局配置
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5000/" //网关暴露的的地址。
  },
  //路由配置
  "ReRoutes": [
    // 第一个api
    {
      /** 万能配置
         "UpstreamPathTemplate": "/first/{url}",
         "DownstreamPathTemplate": "/{url}", 
      **/
      "UpstreamPathTemplate": "/first/{controller}/{action}", //上游Api请求路由规则
      "DownstreamPathTemplate": "/{controller}/{action}", //网关转发到下游路由规则
      "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ], //上下游支持请求方法
      "DownstreamScheme": "http", //下游服务配置
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost", //下游地址
          "Port": 5001 //下游端口号
        }
      ]
    },
    // 第二个api
    {
      /** 万能配置
         "UpstreamPathTemplate": "/second/{url}",
         "DownstreamPathTemplate": "/{url}", 
      **/
      "UpstreamPathTemplate": "/second/{controller}/{action}",
      "DownstreamPathTemplate": "/{controller}/{action}",
      "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ],
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5002
        }
      ]
    }
  ]
}

如图
在这里插入图片描述

8、在WebApiGateway项目的Startup.csConfigureServices方法和Configure方法中配置Ocelot
namespace WebApiGateway
{
    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.AddControllers();
            //添加Ocelot,注意configuration.json的路径,我本身就放在了根路径下
            services.AddOcelot(new ConfigurationBuilder().AddJsonFile("configuration.json", true, true).Build());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //配置使用Ocelot
            app.UseOcelot();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }}

如图
在这里插入图片描述

9、编译之后,启动项目,进入到每个项目的文件夹下,注意不是解决方案文件夹,是项目各自文件夹下
进入项目文件夹中之后,按住shit+鼠标右键,选择“在此处打开powershell窗口”选项,如图,然后输入dotnet run + 回车,启动项目

在这里插入图片描述
在这里插入图片描述
启动成功
在这里插入图片描述

10、访问网关

(1)访问firstApi: (get请求可以直接使用浏览器访问,我是用的是postman)http://localhost:5000/first/firstapi/getmessage在这里插入图片描述
(2)访问sceondApi: (可以直接使用浏览器访问)http://localhost:5000/second/secondapi/getmessage
在这里插入图片描述

总结

可以看到本来应该分别用http://localhost:5001/first/firstapi/getmessage和
http://localhost:5002/second/secondapi/getmessage访问的api,现在只需要改变路由即可访问,即只需要通过全局唯一入口http://localhost:5000/访问其下游api,这就是网关的作用之一:API网关是微服务架构中的唯一入口,它提供一个单独且统一的API入口用于访问内部一个或多个API。

参考文章

Net Core使用Ocelot网关(一) -负载,限流,熔断,Header转换
Asp.Net Core + Ocelot 网关搭建:路由简单配置

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值