ASP.NET Core 微服务,基于Ocelot API 网关的微服务
介绍
今天我们将学习微服务架构及其在 ASp.Net Core – 3.1 中使用 Ocelot API Gateway 的实现。我们都知道将微服务用于大规模应用程序的好处。
微服务架构 – 概述
有两种可能的方法来构建和构建应用程序:
- 单体架构
- 微服务架构
单体架构
Monolith 就像一个大容器,应用程序的所有软件组件都在其中组装并紧密耦合;即每个组件完全相互依赖。Monolith 有优点也有缺点。与微服务相比,单体架构的优势较少。
坏处
发展缓慢
如果我们修改任何模块或任何组件,我们需要重新部署整个应用程序而不是更新它的一部分。它在缓慢的开发中消耗更多的时间。
不可靠
如果一项服务出现故障,则整个应用程序将停止工作,因为该应用程序的所有服务都相互连接。
大型复杂应用
对于大规模应用,维护起来很困难,因为它们相互依赖。
它消耗更多内存,其中每个组件都将访问整个数据,并且会消耗更多内存并重建应用程序。除此之外,我们需要更改整个应用程序,这使该过程有点困难。
微服务架构
微服务架构是指一种技术,它通过将应用程序分解为实现特定业务功能的离散服务,为现代开发人员提供一种设计高度可扩展、灵活的应用程序的方法。这些服务通常被称为“松散耦合”,可以独立构建、部署和扩展。
下图来自Microsoft Docs,展示了微服务架构风格。
微服务创建
创建空白解决方案
创建一个名为 Microservices 的新解决方案文件夹
-> 右键单击微服务文件夹
-> 点击添加
-> 点击新建项目
创建客户微服务
-> 输入项目名称
-> 选择 API 作为模板,我们将使用 .Net Core 3.1 版本。
-> 点击创建
创建产品微服务
– > 遵循与我们为客户微服务所做的相同的过程。
创建 API 网关
-> 选择 Empty 作为具有相同 .Net Core 3.1 版本的模板。
文件夹结构
配置 Ocelot API 网关
这就是 Ocelot API 网关在我们项目中的工作方式。
要了解 Ocelot 及其功能,请访问此链接 Ocelot API Gateway
安装Gateway.WebAPI下的包
Install-Package Ocelot
在 Startup.cs 中添加配置设置
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
namespace Gateway.WebApi
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
await app.UseOcelot();
}
}
}
在 Gateway.WebAPI 下创建 configuration.Json 文件,定义微服务所需的 Routes。
configuration.Json

运行项目以检查结果。
输出
产品微服务——end point
客户微服务 -end point
注意
我还在这个中实现了 Swagger 来检查单个微服务的结果。
希望这篇文章能帮到你!
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!