zoukankan      html  css  js  c++  java
  • .Netcore 2.0 Ocelot Api网关教程(1)- 入门

    Ocelot(Github)
    Ocelot官方文档(英文)
    本文不会介绍Api网关是什么以及Ocelot能干什么
    需要对Api网关及Ocelot有一定的理论了解

    开始使用Ocelot搭建一个入门级Api网关

    1.新建3个WebApi项目,分别命名为OcelotGetway、WebApiA、WebApiB

     
    webapi项目.png
    • OcelotGetway项目用于做Api网关
    • WebApiA、WebApiB作为两个api接口服务

    2.在OcelotGetway项目的Nuget包管理器中搜索Ocelot并安装

     
    Nuget包管理器.png


    或者在程序包管理器中输入
    Install-Package Ocelot安装

    3.在OcelotGetway项目中新建json文件并命名为configuration.json在VS中右键修改为“始终复制”

     
    configuration.json.png

    4.编辑configuration.json文件并添加以下内容

    {
      "ReRoutes": [
        {
          "DownstreamPathTemplate": "/api/values",
          "DownstreamScheme": "http",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 5001
            }
          ],
          "UpstreamPathTemplate": "/webapia/values",
          "UpstreamHttpMethod": [ "Get" ]
        },
        {
          "DownstreamPathTemplate": "/api/values",
          "DownstreamScheme": "http",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 5002
            }
          ],
          "UpstreamPathTemplate": "/webapib/values",
          "UpstreamHttpMethod": [ "Get" ]
        }
      ]
    }
    

    5.修改OcelotGetway项目的Startup类如下

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    
        services.AddOcelot(new ConfigurationBuilder()
                .AddJsonFile("configuration.json")
                .Build());
    }
    
    public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        
        await app.UseOcelot();
    
        app.UseMvc();
    }
    

    6.修改WebApiA和WebApiB项目的ValuesController分别为

    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1 from webapi A", "value2 from webapi A" };
    }
    
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1 from webapi B", "value2 from webapi B" };
    }
    

    7.编辑Properties目录下的launchSettings.json文件中的applicationUrl(每个文件中有两个,只改下边的就可以)

     
    launchSettings.json.png

    分别设置3个项目的applicationUrl为:

    8.分别运行WebApiA、WebApiB、OcelotGetway
    浏览器分别访问
    http://localhost:5000/webapia/values
    http://localhost:5000/webapib/values

     
    运行效果.png


    源码下载

    完,下一篇将介绍路由

    作者:Weidaicheng
    链接:https://www.jianshu.com/p/c967eda8b04d
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 相关阅读:
    javascript
    自己动手、丰衣足食!<菜单导航栏------不简单>
    补---div渐变色条
    自己动手、丰衣足食!<箭头 → ← → ← ---2>
    自己动手、丰衣足食!<箭头 → ← → ← ---1>
    6.19 抽象类
    6.19 多态
    6.19 提纲
    6.18 继承
    6.18 (继承+(四类访问修饰符+程序集+静态方法))提纲
  • 原文地址:https://www.cnblogs.com/lhxsoft/p/11724693.html
Copyright © 2011-2022 走看看