简介

  api网关是提供给外部调用的统一入口,类似于dns,所有的请求统一先到api网关,由api网关进行指定内网链接。

  ocelot是基于netcore开发的开源api网关项目,功能强大,使用方便,它包含了负载均衡、路由、请求聚合、服务发现、权限认证等功能。

基础准备

  开发环境:vs2017

  netcore:2.1

新建项目

  

 

 

netcore安装ocelot

  • install-package ocelot  安装ocelot组件

配置ocelot

 1.添加ocelotsettings.json文件,并且在program.cs文件当中添加配置信息

 

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 ocelottest
{
    public class program
    {
        public static void main(string[] args)
        {
            buildwebhost(args).run();
        }

        public static iwebhost buildwebhost(string[] args) =>
         webhost.createdefaultbuilder(args)
             .usestartup<startup>()
            .useurls("http://localhost:8683")
         .configureappconfiguration(conf => {
             conf.addjsonfile("ocelotsettings.json", optional: false, reloadonchange: true);
         })
             .build();
    }
}

2.注入ocelot服务

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.builder;
using microsoft.aspnetcore.hosting;
using microsoft.aspnetcore.mvc;
using microsoft.extensions.configuration;
using microsoft.extensions.dependencyinjection;
using microsoft.extensions.logging;
using microsoft.extensions.options;
using ocelot.dependencyinjection;
using ocelot.middleware;
using ocelot.provider.consul;
using ocelot.provider.polly;

namespace ocelottest
{
    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)
        {
            //注入ocelot服务
            services.addocelot(configuration).addconsul().addpolly();
        }

        // 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();
        }
    }
}

3.配置ocelotsettings.json

{
  "reroutes": [

    {
      //下游路由模板,真实请求的路径
      "downstreampathtemplate": "/api/{everything}",
      //请求的方式,例如:http,https
      "downstreamscheme": "http",
      //服务器名称
      "servicename": "zyz",
      //启用consul服务
      "useservicediscovery": true,
      //服务熔断
      "qosoptions": {
        "exceptionsallowedbeforebreaking": 3, //允许多少次异常请求
        "durationofbreak": 5, //熔断时间,单位为秒
        "timeoutvalue": 5000 //如果下游请求的处理时间超过多少则自动设置超时
      },
      "httphandleroptions": {
        "allowautoredirect": false,
        "usecookiecontainer": false,
        "usetracing": false
      },
      "rerouteiscasesensitive": false,
      //负载均衡:
      //roundrobin轮流发送;
      //leastconnection – 将请求发往最空闲的那个服务器
      //noloadbalance – 总是发往第一个请求或者是服务发现
      "loadbalanceroptions": {
        "type": "roundrobin"
      },
      //上游地址配置
      "upstreampathtemplate": "/test/{everything}",
      //上游支持的请求类型
      "upstreamhttpmethod": [ "post", "get" ]
    }
  ],
  "globalconfiguration": {
    "baseurl": "https://localhost:8683",
    //consul服务器地址和ip
    "servicediscoveryprovider": {
      "host": "localhost",
      "port": 8500
    }
  }
}

4.启动ocelot项目和consul服务。

把服务注册到consul当中,通过postman发送请求测试,成功转发消息,并且实现负载均衡。

 

 

小结:简单的ocelot搭建完成,后续的一些扩展功能慢慢在研究。

快速入口:

快速入口: 

快速入口: