一夫當關萬夫莫開
一:源起:
當我們的應用不再是單體架構時,微服務將原先單體下的功能組件分割後,產生了許多個微服務,實際上我們還是以前那樣的操作,訪問服務接口,達到我們的目的,而這次不過是換成了http(s)請求的微服務,以前的服務接口也是有base服務以便掛載一些通用處理,所以這裏分化出去的微服務也是要一個統一的入口或者稱之爲管家的東西來管理與分發。那麼API網關這樣一個概念就呼之欲出了,這裏將記錄.net core開源的網關 Ocelot 的使用。
二:搬磚:
此處流程只是Ocelot作爲網關轉發請求的簡單demo,代碼設置源自網上,部分自己瞎改
環境:
vs2017 || .net core 2.0 || Ocelot 8.0.0
1.創建網關api(nuget或者其他引入Ocelot的依賴),以及2個微服務api。
2.網關api這裏我省去了原有的(control以及mvc服務)
Ocelot配置文件
{
"ReRoutes": [
//微服務一配置:
{
"DownstreamPathTemplate": "/api/get",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 60001
}
],
"UpstreamPathTemplate": "/api/get",
"UpstreamHttpMethod": [ "Get" ]
},
//微服務二配置:
{
"DownstreamPathTemplate": "/api/post",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 60002
}
],
"UpstreamPathTemplate": "/api/post",
"UpstreamHttpMethod": [ "Get" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "localhost:60000"
}
}
網關api設置:
在 Program.cs添加Ocelot的配置文件
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
//此處添加Ocelot的配置
.ConfigureAppConfiguration((hostingContext, builder) => {
builder
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("ocelot.json");
})
.UseStartup<Startup>()
.Build();
在Startup.cs添加Ocelot服務
public void ConfigureServices(IServiceCollection services)
{
//添加網關配置
services.AddOcelot(Configuration);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseOcelot().Wait();
}
2個微服務就是普通的設置:
namespace MicroServicePost.Controllers
{
[Route("api/[controller]")]
public class PostController : Controller
{
[HttpGet]
public IEnumerable<string> yishuiPost()
{
return new string[] { "易", "水", "POST" };
}
}
}
這裏是調試啓動3個進程,且Ocelot的配置需要明確的地址,所以端口要麼是看api各自屬性裏面設定的要麼就是統一改下佔用端口,且調試啓動3個端口需要到解決方案屬性那裏設定,且這3個進程同屬於一個解決方案內,後續的部署將是啓動docker而不是這樣圖方便一個解決方案啓動的方式。
運行結果如下:
當往網關輸入對應的微服務路由時,你能看到不同服務的回調,當然實際上微服務端口還是需要禁止訪問的,對外面只是暴露80端口這個就是後話了。