当前位置:网站首页>(2) ASP.NET Core3.1 Ocelot routing
(2) ASP.NET Core3.1 Ocelot routing
2020-11-06 20:13:00 【itread01】
1. route
We've covered the previous chapter Ocelot, I believe you also know that ,Ocelot The main function is to receive the client and other incoming HTTP Ask for , And forward it to downstream Services .Ocelot At present, there is only another http This function is supported in the form of a request ( It could be any transport mechanism in the future ).
Ocelot Route one request to another . In order to make Ocelot Normal work , You need to set one in the configuration Route. Now let's just Ocelot The basic project construction introduces the routing function .
2.Ocelot Base project build (APIGatewayBasicDemo)
Now we are based on GitHub Contributors open source projects to learn Ocelot, According to download Ocelot In terms of the basic project structure , We can see that there is a gateway project (APIGateway), A client API Project (CustomersAPIServices), A product API Project (ProductsAPIServices). As shown in the figure below :
2.1Ocelot Gate configuration
APIGateway The gateway project root directory has a configuration.json Configuration file , The content is as follows :
{
//Routes: Object processing upstream requests ( Client ), Every array {} Configuration : Upstream address and corresponding downstream address
"Routes": [
{
// With Downstream At the beginning , Is the address to forward to the downstream server (CustomersAPIServices), And nginx Forwarding is similar to
// All of the following Downstream At the beginning , Form a forwarding url, The forwarding address is http://localhost:9001/api/customers
"DownstreamPathTemplate": "/api/customers",
"DownstreamScheme": "http",
// "DownstreamHost": "localhost",
// "DownstreamPort": 9001,
// Hosts and ports forwarded to downstream servers .
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 9001
}
],
//Upstream It starts with the upstream server ( Client ) Visit address , Through http get Way to visit .
// In other words, client access http://localhost:9000/customers It was actually forwarded to http://localhost:9001/api/customers The service of
"UpstreamPathTemplate": "/customers",
"UpstreamHttpMethod": [ "Get" ]
},
{
"DownstreamPathTemplate": "/api/customers/{id}",
"DownstreamScheme": "http",
// "DownstreamHost": "localhost",
// "DownstreamPort": 9001,
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 9001
}
],
"UpstreamPathTemplate": "/customers/{id}",
"UpstreamHttpMethod": [ "Get" ]
},
{
"DownstreamPathTemplate": "/api/products",
"DownstreamScheme": "http",
// "DownstreamPort": 9002,
// "DownstreamHost": "localhost",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 9002
}
],
"UpstreamPathTemplate": "/products",
"UpstreamHttpMethod": [ "Get" ]
}
],
// Global configuration , Allow to override Routes Specific settings
"GlobalConfiguration": {
"RequestIdKey": "OcRequestId",
"AdministrationPath": "/administration"
}
}
Let's explain these attributes in the file :
DownstreamPathTemplate: Downstream routing service address .
DownstreamScheme: Downstream service address access protocol type http perhaps https.
DownstreamHostAndPorts: It's a data set , Used to define the host and port of any downstream service to which you want to forward requests . Usually , It contains only one entry , But sometimes you may want to make load balancing requests to downstream Services ,Ocelot Allows you to add multiple entries , Then select a load balancer .
UpstreamPathTemplate: Upstream service address , That is, the real access address of downstream services .
UpstreamHttpMethod: Upstream services HTTP How to request , for example Get、Post.
GlobalConfiguration: As the name suggests, it's global configuration , The configuration of this node allows overriding Routes Configuration inside , You can do some general configuration information here .
stay Ocelot in , You can use {something} Add placeholders for variables to the template . The place holder variable needs to exist at the same time DownstreamPathTemplate and UpstreamPathTemplate Attribute . When set to Ocelot When ,Ocelot Will try for each request Ocelot The program will UpstreamPathTemplate Replace the value in the placeholder with DownstreamPathTemplate. For example, the above /customers/{id}.
2.2Core Add in project Ocelot Support
Now we are core Add in project Ocelot Support , The code is as follows :
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
//.UseStartup<Startup>()
// Set the gate url
.UseUrls("http://*:9000")
.ConfigureAppConfiguration((hostingContext, config) =>
{
// newly added Ocelot Configuration file
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("configuration.json")
.AddEnvironmentVariables();
})
.ConfigureServices(s =>
{
// newly added Ocelot Service
s.AddOcelot();
s.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
})
.Configure(a =>
{
// Use Ocelot Intermediary software
a.UseOcelot().Wait();
});
Ocelot The configuration of the above code is basically completed , Let's look at a foundation Ocelot Routing normal workflow .
CustomersAPIServices Project's CustomersController There are two ways :
[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}";
}
}
ProductsAPIServices Project's ProductsController There is one way :
[Route("api/[controller]")]
public class ProductsController : Controller
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "Surface Book 2", "Mac Book Pro" };
}
}
The above three downstream routing addresses are based on configuration.json The configuration files are configured with upstream distribution address respectively , According to the configuration information, the three projects are listed in IIS Put it on the top , Of course, you can also use dotnet run Command to start the three projects respectively .APIGateway、CustomersAPIServices、ProductsAPIServices The project binding hosts are http://localhost:9000、http://localhost:9001、http://localhost:9002.
When we open the browser http://localhost:9000/customers When , You will find that the browser outputs the following information :
Why enter the gateway host address , It's the result of the client's processing ? That's because when clients access upstream services http://localhost:9000/customers When ,Ocelot Requests will be distributed to http://localhost:9001/api/Customers/Get To deal with , Then return the result .
And when we turn on http://localhost:9000/customers/1 When , It will also output the following information :
Configuration information upstream template /customers/{id} Corresponding to the downstream template /api/customers/{id}, When the path we request is http://localhost:9000/customers/1 When ,Ocelot It will be distributed to the corresponding downstream route according to the configuration information http://localhost:9001/api/Customers/Get/1 To deal with , Then return the result .
Empathy , When the client accesses the upstream service http://localhost:9000/products When ,Ocelot It will also be distributed to the corresponding downstream routes http://localhost:9002/api/Products To deal with , Then return the result :
According to the above test results , That is to say, our Ocelot It's already working , And according to the upstream and downstream routes are mapped . Of course, this chapter is only a brief introduction Ocelot Routing functions , and configuration.json Some properties in the configuration have not been described yet , For example, load balancing 、 Current limiting , Fuse, etc . I'm going to continue with this GitHub The contributor open source project continues to explain its functionality .
References :
Ocelot Official website
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
边栏推荐
- The importance of big data application is reflected in all aspects
- 华为Mate 40 系列搭载HMS有什么亮点?
- Outsourcing is really difficult. As an outsourcer, I can't help sighing.
- Pattern matching: The gestalt approach一种序列的文本相似度方法
- Music generation through deep neural network
- What if the front end doesn't use spa? - Hacker News
- 視覺滾動[反差美]
- [efficiency optimization] Nani? Memory overflow again?! It's time to sum up the wave!!
- 每个大火的“线上狼人杀”平台,都离不开这个新功能
- 一部完整的游戏,需要制作哪些音乐?
猜你喜欢

前端未來趨勢之原生API:Web Components

It is really necessary to build a distributed ID generation service

C + + and C + + programmers are about to be eliminated from the market

Live broadcast preview | micro service architecture Learning Series live broadcast phase 3

仅用六种字符来完成Hello World,你能做到吗?

零基础打造一款属于自己的网页搜索引擎

Use modelarts quickly, zero base white can also play AI!

The importance of big data application is reflected in all aspects

Pattern matching: The gestalt approach一种序列的文本相似度方法

【自学unity2d传奇游戏开发】如何让角色动起来
随机推荐
Read the advantages of Wi Fi 6 over Wi Fi 5 in 3 minutes
Free patent download tutorial (HowNet, Espacenet)
用一个例子理解JS函数的底层处理机制
一篇文章教会你使用Python网络爬虫下载酷狗音乐
ES6学习笔记(二):教你玩转类的继承和类的对象
一部完整的游戏,需要制作哪些音乐?
GUI engine evaluation index
The importance of big data application is reflected in all aspects
Wechat applet: prevent multiple click jump (function throttling)
代码生成器插件与Creator预制体文件解析
vue任意关系组件通信与跨组件监听状态 vue-communication
How to customize sorting for pandas dataframe
開源一套極簡的前後端分離專案腳手架
常用SQL语句总结
一篇文章带你了解HTML表格及其主要属性介绍
每个大火的“线上狼人杀”平台,都离不开这个新功能
Solve the problem of database insert data garbled in PL / SQL developer
What are the common problems of DTU connection
How to hide part of barcode text in barcode generation software
Using NLP and ml to extract and construct web data