简介原文地址

  接下来你会学习,基于asp.net core 用Ocelot实现一个简单的API网关。或许你会疑问什么是API网关,我们先看下面的截图

  

  API网关是访问你系统的入口,它包括很多东西,比如路由(Routing),身份验证(Authentication),服务发现(Service discovery),日志(Logging ),等等。

Ocelot

Ocelot提供统一的访问入口,适用于.net开发的微服务或者开发的面向服务架构,可以访问Ocelot获得更多信息。

我会用Ocelot实现一个简单的例子。

Step1

    先创建三个项目,如下所示。

项目名称

项目类型

描述

APIGateway

ASP.NET Core Empty

Demo的入口

CustomersAPIServices

ASP.NET Core Web API

API Service消费者相关操作

ProductsAPIServices

ASP.NET Core Web API

API Service 产品相关操作

Step2

创建两个API services,在CustimersAPIServices项目中创建CustomersController。

[Route("api/[controller]")]
public class CustomersController : Controller
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "Catcher Wong", "James Li" };
} [HttpGet("{id}")]
public string Get(int id)
{
return $"Catcher Wong - {id}";
}
}

 为了确定CustimersAPIServices的应用URL,我们应该在项目的类中添加UseUrls

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://localhost:9001")
.Build();

 在PriductsAPIServices项目中新建ProductsController

[Route("api/[controller]")]
public class ProductsController : Controller
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "Surface Book 2", "Mac Book Pro" };
}
}

  

 同样在项目的类中添加UseUrls

 

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://localhost:9002")
.Build();

注意

    你可以通过项目的属性对应用的URL进行配置。

  

Step3

    运行CustimersAPIServices 和ProductsAPIServices。打开两个cmd终端,cd到两个服务的文件夹位置,输入 "dotnet run" 启动两个项目。

 运行成功如下所示。

Step4

    接下来我们新建 APIGateway项目,首先安装Ocelot安装包。

Install-Package Ocelot

     安装成功后,如下图所示。

Step5

在项目下新建configuration.json如下所示。

{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/customers",
"DownstreamScheme": "http",
"DownstreamHost": "localhost",
"DownstreamPort": ,
"UpstreamPathTemplate": "/customers",
"UpstreamHttpMethod": [ "Get" ]
},
{
"DownstreamPathTemplate": "/api/customers/{id}",
"DownstreamScheme": "http",
"DownstreamHost": "localhost",
"DownstreamPort": ,
"UpstreamPathTemplate": "/customers/{id}",
"UpstreamHttpMethod": [ "Get" ]
},
{
"DownstreamPathTemplate": "/api/products",
"DownstreamScheme": "http",
"DownstreamPort": ,
"DownstreamHost": "localhost",
"UpstreamPathTemplate": "/api/products",
"UpstreamHttpMethod": [ "Get" ]
}
],
"GlobalConfiguration": {
"RequestIdKey": "OcRequestId",
"AdministrationPath": "/administration"
}
}

  该文件是API网关的配置文件,包括两部分,ReRoutes和GlobalConfiguration。

  ReRoutes是告诉Ocelot如何操作上游的request请求,

  GlobalConfiguration有点黑客的感觉,允许对ReRoutes的设置进行重写。

  用下面的片段介绍ReRoutes。

{
"DownstreamPathTemplate": "/api/customers/{id}",
"DownstreamScheme": "http",
"DownstreamHost": "localhost",
"DownstreamPort": ,
"UpstreamPathTemplate": "/customers/{id}",
"UpstreamHttpMethod": [ "Get" ]
}

  以Downstream开头的项意味我们的请求会指向http://localhost:9001/api/customers/{id}

  以Upstream开头的项意味我们应该使用/customers/{id} 的HTTP Get请求去访问服务。

Step6

修改Startup类,使用Ocelot。

public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();
builder.SetBasePath(env.ContentRootPath)
//add configuration.json
.AddJsonFile("configuration.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables(); Configuration = builder.Build();
} //change
public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services)
{
Action<ConfigurationBuilderCachePart> settings = (x) =>
{
x.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug); }).WithDictionaryHandle();
};
services.AddOcelot(Configuration, settings);
} //don't use Task here
public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
await app.UseOcelot();
}
}

  别忘了添加上面的configuration.json文件。

Step7

这一步至关重要,用来配置Ocelot。

我们新建IWebHostBuilder的新实例,不要使用var!!!

public class Program
{
public static void Main(string[] args)
{
IWebHostBuilder builder = new WebHostBuilder();
builder.ConfigureServices(s =>
{
s.AddSingleton(builder);
});
builder.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseUrls("http://localhost:9000"); var host = builder.Build();
host.Run();
}
}

  同样我们需要指明应用的URL。

Step8

启动APIGateway,使用cmd通过dotnet run 命令。启动成功后,输入http://localhost:9000

  当我们通过客户端访问http://localhost:9000/api/products真实的路由是http://localhost:9002/api/products

当我们访问http://localhost:9000/customers,真实的路由http://localhost:9001/api/customers

当我们访问http://localhost:9000/customers/1, 真实的路由是http://localhost:9001/api/customers/1

源码:APIGatewayDemo

百度网盘

链接:https://pan.baidu.com/s/17sqfGcYx8yEHRL_LwKAUlA
提取码:p3d0

总结

这篇文章介绍了通过Ocelot创建API网关。希望可以帮到你。

由于只是简单的示例代码,Ocelot许多重要的特性比如服务发现,身份验证,服务质量(qos),未在示例中体现。

.net core使用ocelot---第一篇 简单使用的更多相关文章

  1. ASP.NET Core 学习笔记 第一篇 ASP.NET Core初探

    前言 因为工作原因博客断断续续更新,其实在很早以前就有想法做一套关于ASP.NET CORE整体学习度路线,整体来说国内的环境的.NET生态环境还是相对比较严峻的,但是干一行爱一行,还是希望更多人加入 ...

  2. VueRouter爬坑第一篇-简单实践

    VueRouter系列的文章示例编写时,项目是使用vue-cli脚手架搭建. 项目搭建的步骤和项目目录专门写了一篇文章:点击这里进行传送 后续VueRouter系列的文章的示例编写均基于该项目环境. ...

  3. .net core番外第一篇:Autofac的几种常见注入方式、生命周期和AOP

    使用Autofac进行服务注册实践: 新建三个项目,分别是webapi项目 Wesky.Core.Autofac以及两个类库项目 Wesky.Core.Interface和Wesky.Core.Ser ...

  4. java 学习第一篇简单基础

    Java基础 Java Java 和C#有着极为相似的语法. 和C#都是面向对象的高级程序语言. JAVA是一个开源,公开的语言,有着极其丰富的开源库和其他资源. JAVA分类 JAVA分SE EE ...

  5. .net core 日常学习第一篇

    使用vs 2015 update3 版本,安装sdk:https://dotnet.microsoft.com/download  可以运行 .net core 1.x版 或者使用vs 2017及以上 ...

  6. .net core使用ocelot---第六篇 负载均衡

    简介 .net core使用ocelot---第一篇 简单使用 .net core使用ocelot---第二篇 身份验证 .net core使用ocelot---第三篇 日志记录  .net core ...

  7. .net core使用ocelot---第二篇 身份验证

    简介原文链接      .net core使用ocelot---第一篇 简单使用 接上文,我将继续介绍使用asp.net core 创建API网关,主要介绍身份验证(authentication )相 ...

  8. .net core使用ocelot---第八篇 Consul

    简介 .net core使用ocelot---第一篇 简单使用   .net core使用ocelot---第二篇 身份验证使用  .net core使用ocelot---第三篇 日志记录  .net ...

  9. .net core使用ocelot---第七篇 服务发现

    简介 .net core使用ocelot---第一篇 简单使用   .net core使用ocelot---第二篇 身份验证使用  .net core使用ocelot---第三篇 日志记录  .net ...

随机推荐

  1. 003.SQLServer数据库镜像高可用部署

    一 数据库镜像部署准备 1.1 数据库镜像支持 有关对 SQL Server 2012 中的数据库镜像的支持的信息,请参考:https://docs.microsoft.com/zh-cn/previ ...

  2. 如何将 qsys 子模块设置为参数可调的方式给另外的qsys 调用

    Intel FPGA Quartus 软件中的 Qsys工具 也就是 Platform Designer 系统集成工具,可以 图形化界面操作 使用系统自带ip,自定义ip 系统自动生成 ip 间的连接 ...

  3. leadcode的Hot100系列--62. 不同路径--简单的动态规划

    题目比较清晰,简单来说就是: A B C D E F G H I J K L 只能往右或者往下,从A到L,能有几种走法. 这里使用动态规划的方法来做一下. 动态规划最重要的就是动态方程,这里简单说下这 ...

  4. NumPy基础操作(3)——代数运算和随机数

    NumPy基础操作(3)--代数运算和随机数 (注:记得在文件开头导入import numpy as np) 目录: NumPy在矩阵运算中的应用 常用矩阵运算函数介绍 编程实现 利用NumPy生成随 ...

  5. mysql计算日期之间相差的天数

    TO_DAYS(NOW()) - TO_DAYS(createTime) as dayFactor,

  6. 小代介绍Spring Boot

    想要获取更多文章可以访问我的博客 - 代码无止境. 小代很顺利的完成了陈BOSS交代给他搭建Spring Boot示例程序的任务.但是小代是一个乐于学习的程序员,他通过一番学习总结了一篇简单介绍Spr ...

  7. (转)Java 8 中的 Streams API 详解

    为什么需要 Stream Stream 作为 Java 8 的一大亮点,它与 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念.它也不同于 StAX 对 ...

  8. EPG开发《异常排查以及解决方案》

    [框架]

  9. C语言指针专题——指针难学的4点原因

    前一篇跟大家聊了聊指针的概念,可是就算了解了指针是什么,为什么依然感觉难学?我试着从几个点切入,聊聊指针难学之处. 文末会给大家推荐几本书,有需要的朋友可以看看! 难点1. 讨厌的星号 定义指针变量p ...

  10. samba搭建与配置说明

    1. 环境检查getenforce 检查selinux service iptables stop 2.安装samba yum -y install samba 3.配置samba /etc/samb ...