c#:Ocelot初体验

环境:

  • window 10 x64
  • vs2019 16.7.4
  • asp.net core 3.1
  • Ocelot 16.0.1

实验代码下载:https://download.csdn.net/download/u010476739/13032294

一、Ocelot介绍和作用

Ocelot是C#开发的,主要用于网关服务的,比如:转发请求、限流等,可类比Nginx

二、体验Ocelot的转发功能

本次体验一下ocelot的转发请求功能,实验的架构如下:
在这里插入图片描述

新建空白解决方案OcelotTrial以及三个WebApi项目如下:
在这里插入图片描述
其中,OcelotDemo为网关项目,它开启后用来将浏览器的请求转发到GoodApiOrderApi服务上,而GoodApiOrderApi为正常的webapi项目。

2.1 准备OrderApi项目

OrderApi项目上新建DemoController控制器,代码如下:

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OrderApi.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class DemoController : ControllerBase
    {
        public string Echo()
        {
            return "OrderApi";
        }
    }
}

配置OrderApi项目的AppSettings.json文件,强制运行url为:http://localhost:5502,配置如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "urls": "http://localhost:5502"
}

2.2 准备GoodApi项目

GoodApi项目上新建DemoController控制器,代码如下:

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GoodApi.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class DemoController : ControllerBase
    {
        public string Echo()
        {
            return "GoodApi";
        }
    }
}

配置GoodApi项目的AppSettings.json文件,强制运行url为:http://localhost:5501,配置如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "urls": "http://localhost:5501"
}

2.3 准备OcelotDemo项目

OcelotDemo项目添加Ocelot包引用:

  <ItemGroup>
    <PackageReference Include="Ocelot" Version="16.0.1" />
  </ItemGroup>

在这里插入图片描述
新建配置文件ocelot.json,如下:

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5501
        }
      ],
      "UpstreamPathTemplate": "/good/{everything}",
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "LoadBalancerOptions": { //这里可以配置多个goodapi实例
        "Type": "RoundRobin"
      }
    },
    {
      "DownstreamPathTemplate": "/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [ //这里可以配置多个orderapi实例
        {
          "Host": "localhost",
          "Port": 5502
        }
      ],
      "UpstreamPathTemplate": "/order/{everything}",
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "LoadBalancerOptions": {
        "Type": "RoundRobin"
      }
    }
  ],
  "GlobalConfiguration": {

  }
}

修改Program.cs文件,将ocelot.json配置文件载入:

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

namespace OcelotDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(config =>
                {
                    config.AddJsonFile("ocelot.json");
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

修改Startup.cs文件,注入Ocelot服务,并在http管道中启用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

namespace OcelotDemo
{
    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();
            services.AddOcelot();//注入Ocelot服务
        }

        // 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();
            }
            app.UseOcelot().Wait();//使用Ocelot中间件
        }
    }
}

2.4 测试效果

将这三个项目编译后分别启动,然后通过网关访问GoodApiOrderApi的服务:

通过网关访问GoodApi服务: http://localhost:5500/good/api/demo/echo
在这里插入图片描述
通过网关访问OrderApi服务:http://localhost:5500/order/api/demo/echo
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jackletter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值