.Net Core微服务入门——Ocelot API网关接入

上一章我们测试了一个简单的Client 端访问Consul实现服务注册与发现,但是现实生产环境我们直接通过Client自行连接Consul实现服务注册与发现,基本是不可行的,我们需要一个统一的入口来连接客户端与服务,统一管理,并做安全认证等。

所以,这里就需要用到Ocelot

Ocelot
官网:https://ocelot.readthedocs.io/
Ocelot正是为.Net微服务体系提供一个统一的入口点,称为:Gateway(网关)。

新建Ocelot项目

1、创建一个空的asp.net core web项目。


2、引入Ocelot包:

3、新增ocelot.json,配置服务api信息:

{"Routes": [{"DownstreamPathTemplate": "/api/product/getall","DownstreamScheme": "http","DownstreamHostAndPorts": [{"Host": "localhost","Port": 5001},{"Host": "localhost","Port": 5002}],"UpstreamPathTemplate": "/api/product/getall","UpstreamHttpMethod": ["Get"],"LoadBalancerOptions": {"Type": "RoundRobin" //负载均衡,轮询机制 LeastConnection/RoundRobin/NoLoadBalancer/CookieStickySessions}}],"GlobalConfiguration": {"BaseUrl": "http://localhost:5010"}
}

这里我们先忽略 Consul,采用直连API服务,因为Consul、Ocelot等组件都是可以独立存在的。

配置文件中的Routes节点用来配置路由:
Downstream代表下游,也就是服务实例,就是我们的服务api地址
如:http://192.168.8.61:5001/api/product/getall
Upstream代表上游,也就是提供给客户端调用的api地址
如:http://192.168.8.61:5010/api/product/getall,
如果这里改成 api1/product/getall,那么客户端访问的api地址就是 http://192.168.8.61:5010/api1/product/getall
上游的路径不一定要和下游一致,可自行配置

LoadBalancerOptions节点用来配置负载均衡:
Ocelot内置了 LeastConnection、RoundRobin、NoLoadBalancer、CookieStickySessions 4种负载均衡策略。
LeastConnection -最少连接,跟踪哪些服务正在处理请求,并把新请求发送到现有请求最少的服务上。该算法状态不在整个Ocelot集群中分布。
RoundRobin - 轮询可用的服务并发送请求。 该算法状态不在整个Ocelot集群中分布。
NoLoadBalancer - 不负载均衡,从配置或服务发现提供程序中取第一个可用的下游服务。
CookieStickySessions - 使用cookie关联所有相关的请求到制定的服务。

BaseUrl节点就是配置我们ocelot网关将要运行的地址。

4、修改Program.cs:

public class Program
{public static void Main(string[] args){CreateHostBuilder(args).Build().Run();}public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{config.AddJsonFile("ocelot.json");}).ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup<Startup>();});
}

5、修改Startup.cs

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=398940public void ConfigureServices(IServiceCollection services){//添加ocelot服务services.AddOcelot();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env){//设置Ocelot中间件app.UseOcelot().Wait();}
}

6、运行Oeclot项目

我们先手动运行 ,直接进入bin目录下,执行控制台命令:`dotnet Ocelot.APIGateway.dll --urls=“http://*:5010”


浏览器访问 http://192.168.8.61:5010/api/product/getall


这里说明Ocelot网关正常运行了,下一步,我们client接入网关

7、修改Client

IGatewayServiceHelper. cs

public interface IGatewayServiceHelper{/// <summary>/// 获取产品数据/// </summary>/// <returns></returns>Task<string> GetProduct();/// <summary>/// 获取服务列表/// </summary>void GetServices();}

GatewayServiceHelper.cs

 public class GatewayServiceHelper: IGatewayServiceHelper{public async Task<string> GetProduct(){var Client = new RestClient("http://localhost:5010");var request = new RestRequest("/api/product/getall", Method.GET);var response = await Client.ExecuteAsync(request);return response.Content;}public void GetServices(){throw new NotImplementedException();}}

Startup.cs

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();注入IServiceHelper//services.AddSingleton<IServiceHelper, ServiceHelper>();//注入IServiceHelperservices.AddSingleton<IGatewayServiceHelper, GatewayServiceHelper>();注入IServiceHelper//services.AddSingleton<IServiceHelper, GatewayServiceHelper>();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.//public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceHelper serviceHelper)public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseHttpsRedirection();app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});//程序启动时 获取服务列表//serviceHelper.GetServices();}
}

ProductsController.cs

[Produces("application/json")]
[Route("product")]public class ProductsController{private readonly IGatewayServiceHelper _serviceHelper;public ProductsController(IGatewayServiceHelper serviceHelper){_serviceHelper = serviceHelper;}/// <summary>/// 获取产品列表/// </summary>/// <returns>产品列表</returns>[Route("GetAll")][HttpGet]public List<Product> GetAllProducts(){var result = _serviceHelper.GetProduct();if (!string.IsNullOrWhiteSpace(result.Result)){var json = result.Result;//将Json转换回图书列表var products = JsonConvert.DeserializeObject<List<Product>>(json);return products;}return null;}}

调试启动Client,浏览器自动打开:https://localhost:44393/product/getall


Client顺利连上了网关层。

有人问,那我api有多个接口怎么办呢,总不能每个接口都配置一下吧。
多个接口的话,只需要修改ocelot.json即可,将具体api接口 改成 api/{url}

{"Routes": [{"DownstreamPathTemplate": "/api/{url}","DownstreamScheme": "http","DownstreamHostAndPorts": [{"Host": "localhost","Port": 5001},{"Host": "localhost","Port": 5002}],"UpstreamPathTemplate": "/api/{url}","UpstreamHttpMethod": ["Get"],"LoadBalancerOptions": {"Type": "RoundRobin" //负载均衡,轮询机制 LeastConnection/RoundRobin/NoLoadBalancer/CookieStickySessions}}],"GlobalConfiguration": {"BaseUrl": "http://localhost:5010"}
}

那如果有多个Service呢

{"Routes": [{"DownstreamPathTemplate": "/api/{url}","DownstreamScheme": "http","DownstreamHostAndPorts": [{"Host": "localhost","Port": 5001},{"Host": "localhost","Port": 5002}],"UpstreamPathTemplate": "/api/{url}","UpstreamHttpMethod": ["Get"],"LoadBalancerOptions": {"Type": "RoundRobin" //负载均衡,轮询机制 LeastConnection/RoundRobin/NoLoadBalancer/CookieStickySessions}},{"DownstreamPathTemplate": "/api/{url}","DownstreamScheme": "http","DownstreamHostAndPorts": [{"Host": "localhost","Port": 5005},{"Host": "localhost","Port": 5006}],"UpstreamPathTemplate": "/api/{url}","UpstreamHttpMethod": ["Get"],"LoadBalancerOptions": {"Type": "RoundRobin" //负载均衡,轮询机制 LeastConnection/RoundRobin/NoLoadBalancer/CookieStickySessions}}],"GlobalConfiguration": {"BaseUrl": "http://localhost:5010"}
}

下一章,我们将继续深入,探讨Ocelot 连接 Consul,服务治理等

https://blog.csdn.net/weixin_41003771/article/details/119177786

.Net Core微服务入门——Ocelot API网关接入(一)相关推荐

  1. .Net Core微服务入门——Ocelot API网关接入(二)

    Net Core微服务入门--Ocelot API网关接入(二) 我们先接入Consul,实现服务发现 服务发现 1.引入 Ocelot.Provider.Consul 包 2.修改ocelot.js ...

  2. .Net Core微服务入门——Ocelot和Consul集群高可用

    .Net Core微服务入门--Ocelot和Consul集群高可用 上一章 我们ocelot网关顺利的接入了consul集群,并且访问成功. 但是,我们也遇到了问题,把 192.168.8.25 上 ...

  3. .net core ocelot 获取路由的mothed_Net Core微服务入门全纪录(四)Ocelot网关(上)

    上一篇[.Net Core微服务入门全纪录(三)--Consul-服务注册与发现(下)]已经使用Consul完成了服务的注册与发现,实际中光有服务注册与发现往往是不够的,我们需要一个统一的入口来连接客 ...

  4. swagger 返回json字符串_Net Core微服务入门全纪录(完结)——Ocelot与Swagger

    前言 上一篇[.Net Core微服务入门全纪录(八)--Docker Compose与容器网络]完成了docker-compose.yml文件的编写,最后使用docker compose的一个up指 ...

  5. .Net Core微服务入门全纪录(完结)——Ocelot与Swagger

    点击上方蓝字"小黑在哪里"关注我吧 前言 上一篇[.Net Core微服务入门全纪录(八)--Docker Compose与容器网络]完成了docker-compose.yml文件 ...

  6. .Net微服务架构:API网关

    本人建立了个人技术.工作经验的分享微信号,计划后续公众号同步更新分享,比在此更多具体.欢迎有兴趣的同学一起加入相互学习.基于上篇微服务架构分享,今天分享其中一个重要的基础组件"API网关&q ...

  7. .NET微服务架构及API网关

    .NET微服务架构及API网关 原文:.NET微服务架构及API网关 一.MSA简介 1.1.MSA是什么 微服务架构MSA是Microservice Architecture的简称,它是一种架构模式 ...

  8. 万字长文解析:分布式架构、SOA、微服务架构、API网关、ESB服务总线架构之间的关联及演进

    1架构演进 架构十五年:改变的是形态,不变的是目的 业务驱动架构形态变化 过去十几年,随着互联网发展以及业务的多样化,系统的架构也在不断发生变化,总体上来说大体经历了从单体应用架构-垂直应用架构-分布 ...

  9. spring cloud+dotnet core搭建微服务架构:Api网关(三)

    前言 国庆假期,一直没有时间更新. 根据群里面的同学的提问,强烈推荐大家先熟悉下spring cloud.文章下面有纯洁大神的spring cloud系列. 上一章最后说了,因为服务是不对外暴露的,所 ...

最新文章

  1. Linux 下hosts文件
  2. 与太原工业学院商讨第十七届全国大学生智能车华北赛区承办事宜
  3. 【django】HttpResponse对象
  4. linux虚拟内存当硬盘,linux里面虚拟内存和swap有什么不同?
  5. Lucene学习总结之四:Lucene索引过程分析
  6. 女人 这20种男人你永远不必等
  7. jQuery .tmpl(), .template()学习
  8. 信息时代不被淘汰,获取成功需有的十种能力
  9. 常见掌握类库与工具体系图 艾提拉总结 Atitit 文档资料处理重要类库与工具体系树 Configuration yml xml jsoup  Net apache commons net
  10. Variational Mode Decomposition(变分模态分解),介绍,算法流程,作用,优缺点
  11. 季节性ARIMA模型【R语言】
  12. python 英语翻译 excel_Excel自动翻译
  13. 【2021最新版】Kafka面试题总结(25道题含答案解析)
  14. 如何用十步写一首原创歌曲
  15. 所以,FileWriter和BufferedWriter的真正区别在哪
  16. python十进制转换_python 十进制转换成任意进制
  17. 通信室计算机室采购配置co2灭火器,2019一级消防案例分析考点:民用类建筑消防设施的配置...
  18. 简单扑克牌游戏C语言,【算法】C语言实现简易的扑克牌游戏
  19. 1050: [HAOI2006]旅行comf
  20. C++ 点(.)操作符和箭头(-)操作符

热门文章

  1. 贵金属白银基本知识:各白银品种之对比
  2. c语言月考及答案,c语言试题月考.docx
  3. 按钮宽度和高度固定,字体大小根据字数自适应用的javascript实现
  4. css 圆形光晕,CSS实现运动光环
  5. 深度学习——日常小点积累
  6. 什么是MVVM,MVVM和MVC的区别?
  7. joa-framework 工作流快速开发框架 jeecg官方工作流版本 发布
  8. 辟谣:Defaulting to user installation because normal site-packages is not writeable
  9. iOS网络诊断功能 ping traceroute
  10. 虚拟机上的ubuntu安装RT系统+安装IGH