Ocelot 作用
1. 路由---核心功能
2. 集群負(fù)載均衡
上一章Consul做到了集群、自動(dòng)注冊(cè)發(fā)現(xiàn)和健康檢測(cè)《.Net Core 3.x MVC Consul 集群》,可是存在問(wèn)題灭忠,就是前端實(shí)例需要寫很多調(diào)用Consul和后端服務(wù)實(shí)例的代碼浓镜,如果有改動(dòng)华弓,所有前端都需要改動(dòng)發(fā)布梁厉。這時(shí)候需要有個(gè)網(wǎng)關(guān)來(lái)把這些請(qǐng)求集合起來(lái)做處理(Ocelot + Consul)暗挑。
Ocelot 實(shí)現(xiàn)了客戶端和服務(wù)實(shí)例的隔絕—保護(hù)—節(jié)約IP—提高效率
Consul 實(shí)現(xiàn)了集群管理,發(fā)現(xiàn)—健康檢查—下線
官網(wǎng):https://threemammals.com/ocelot
Git:https://github.com/ThreeMammals/Ocelot
1. 添加一個(gè) Web Api 項(xiàng)目?
2. 引用 Ocelot 和 Ocelot.Provider.Consul 兩個(gè)包
3. 添加 配置文件
U001是網(wǎng)關(guān)地址(自定義)
UserService 就是 后端服務(wù)實(shí)例里注冊(cè)Consul時(shí)設(shè)置的分組
http://127.0.0.1:8005 笋除,端口 8005 是 啟動(dòng)這個(gè)Gateway實(shí)例使用的端口號(hào) 自定義的
修改?Startup.cs ,注釋默認(rèn)的管道和服務(wù)炸裆,添加 Ocelot
修改?Program.cs 垃它,讀取 剛才添加的?Ocelot 配置文件?configuration.json
生成編譯
這次用到實(shí)例? 后端實(shí)例(AspNetCore.MicroService.ServiceInstance)、Ocelot實(shí)例(AspNetCore.MicroService.Gateway) 和? consul
先啟動(dòng)?consul 命令
consul.exe agent -dev
后端項(xiàng)目bin->編譯項(xiàng)目目錄 啟動(dòng)三個(gè)實(shí)例
dotnet AspNetCore.MicroService.ServiceInstance.dll --urls=”http://*:8002” --ip=”127.0.0.1” --port=8002
dotnet AspNetCore.MicroService.ServiceInstance.dll --urls=”http://*:8003” --ip=”127.0.0.1” --port=8003
dotnet AspNetCore.MicroService.ServiceInstance.dll --urls=”http://*:8004” --ip=”127.0.0.1” --port=8004
Ocelot實(shí)例bin->編譯項(xiàng)目目錄 啟動(dòng)實(shí)例
dotnet AspNetCore.MicroService.Gateway.dll --urls=”http://*:8005” --ip=”127.0.0.1” --port=8005
啟動(dòng)好這些項(xiàng)目就可以訪問(wèn)一下網(wǎng)關(guān)地址了
http://localhost:8005/U001/users/all
按F5刷新,這里Ocelot實(shí)現(xiàn)負(fù)載均衡,自動(dòng)輪詢請(qǐng)求三個(gè)后端實(shí)例国拇。