在實(shí)際的應(yīng)用當(dāng)中,經(jīng)常會(huì)遇到同一個(gè)操作要請(qǐng)求多個(gè)api來執(zhí)行。這里先假設(shè)一個(gè)應(yīng)用場(chǎng)景:通過姓名獲取一個(gè)人的個(gè)人信息(性別、年齡),而獲取每種個(gè)人信息都要調(diào)用不同的api泣栈,難道要依次調(diào)用嗎卜高?在Ocelot中為我們提供了很好的解決方法。
路由聚合
繼續(xù)使用前邊的文章建立的項(xiàng)目南片,在WebApiA項(xiàng)目中添加一個(gè)新的WebApi控制器命名為UserController,代碼如下:
[Produces("application/json")]
[Route("api/[controller]/[action]")]
public class UserController : Controller
{
[HttpGet]
public string GetSex(string name)
{
if (name == "Jonathan")
return "Man";
return null;
}
[HttpGet]
public int? GetAge(string name)
{
if (name == "Jonathan")
return 24;
return null;
}
}
啟動(dòng)WebApiA,然后使用Postman分別訪問
http://localhost:5001/api/User/GetSex?name=Jonathan
http://localhost:5001/api/User/GetAge?name=Jonathan
結(jié)果如下:
修改configuration.json文件扭倾,向ReRoutes節(jié)點(diǎn)中添加如下配置:
{
"DownstreamPathTemplate": "/api/User/GetSex",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}],
"UpstreamPathTemplate": "/Sex",
"UpstreamHttpMethod": [ "Get" ],
"Key": "Sex"
},
{
"DownstreamPathTemplate": "/api/User/GetAge",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}],
"UpstreamPathTemplate": "/Age",
"UpstreamHttpMethod": [ "Get" ],
"Key": "Age"
}
在與ReRoutes同級(jí)的位置添加如下配置:
"Aggregates": [
{
"ReRouteKeys": [
"Sex",
"Age"
],
"UpstreamPathTemplate": "/GetUserInfo"
}]
請(qǐng)求聚合執(zhí)行的操作為:當(dāng)請(qǐng)求GetUserInfo時(shí)信殊,自動(dòng)到Reoutes中查找ReRouteKeys下Key值相同的路由,并全部請(qǐng)求伞广,然后將請(qǐng)求結(jié)果拼成Json格式返回拣帽。
Postman訪問http://localhost:5000/GetUserInfo疼电,結(jié)果如下:
Ocelot請(qǐng)求聚合現(xiàn)在只支持get方法,點(diǎn)擊https://github.com/ThreeMammals/Ocelot/blob/master/src/Ocelot/Configuration/File/FileAggregateReRoute.cs查看源碼及注釋說明减拭。
請(qǐng)求聚合的頁面404
請(qǐng)求聚合下不會(huì)對(duì)404的頁面返回任何結(jié)果蔽豺,我們現(xiàn)在在configuration.json文件中的ReRoutes節(jié)點(diǎn)下添加如下內(nèi)容:
{
"DownstreamPathTemplate": "/api/User/GetID",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}],
"UpstreamPathTemplate": "/ID",
"UpstreamHttpMethod": [ "Get" ],
"Key": "ID"
}
向Aggregates節(jié)點(diǎn)下的ReRoutesKeys節(jié)點(diǎn)下添加一個(gè)ID
注意:在WebApiA項(xiàng)目中是沒有/api/User/GetID方法的,所以會(huì)返回404
然后我們啟動(dòng)項(xiàng)目訪問http://localhost:5000/api/GetUserInfo拧粪,結(jié)果如下:
可以看到返回的數(shù)據(jù)中ID為空修陡。
源碼下載