Asp.Net Core + Ocelot 网关搭建:路由简单配置

本文介绍使用Ocelot作为API网关的实践过程,通过配置实现不同服务的路由转发,包括用户服务和文章服务,展示了如何将Ocelot集成到项目中并设置路由规则。

前言

  Ocelot是一个基于中间件的网关实现,功能有很多。从浅入深简单学习并记录一下吧。本篇就是一个简单的路由配置实现。

DEMO 搭建

  首先建立三个项目。Api.User,Api.Article,Api.GateWay.ApiGateWay项目中引入Ocelot Nuget包.添加配置文件Ocelot.json.

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/{all}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 60001
        }
      ],
      "UpstreamPathTemplate": "/user/{all}",
      "UpstreamHttpMethod": ["GET","POST"]
    },
    {
      "DownstreamPathTemplate": "/{all}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 60002
        }
      ],
      "UpstreamPathTemplate": "/article/{all}",
      "UpstreamHttpMethod": ["GET","POST"]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:60003/"
  }
}

  启动的时候将配置文件加进去,并且Startup中添加相应的中间件:services.AddOcelot(),app.UseOcelot();

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration((hostingContext, config) =>
             {
                 config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                       .AddJsonFile("ocelot.json", optional: true, reloadOnChange: true)
                       .AddEnvironmentVariables();
             }).UseStartup<Startup>();

  启动三个项目,运行效果如下:
841545-20181019162915056-492422857.png

总结

  这样就能实现将网关做为统一入口,统一管理了。后续在加上各种Ocelot的功能实现。

转载于:https://www.cnblogs.com/panzi/p/9817159.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值