javascript
Spring Cloud 入门 之 Zuul 篇(五)
一、前言
隨著業(yè)務(wù)的擴(kuò)展,微服務(wù)會(huì)不對(duì)增加,相應(yīng)的其對(duì)外開放的 API 接口也勢(shì)必增多,這不利于前端的調(diào)用以及不同場(chǎng)景下數(shù)據(jù)的返回,因此,我們通常都需要設(shè)計(jì)一個(gè) API 網(wǎng)關(guān)作為一個(gè)統(tǒng)一的 API 入口,來組合一個(gè)或多個(gè)內(nèi)部 API。
二、簡單介紹
#?2.1 API 網(wǎng)關(guān)使用場(chǎng)景
黑白名單: 實(shí)現(xiàn)通過 IP 地址控制請(qǐng)求的訪問日志:實(shí)現(xiàn)訪問日志的記錄,進(jìn)而實(shí)現(xiàn)日志分析,處理性能指標(biāo)等協(xié)議適配:實(shí)現(xiàn)通信協(xié)議的校驗(yàn)、適配轉(zhuǎn)換的功能身份認(rèn)證:對(duì)請(qǐng)求進(jìn)行身份認(rèn)證計(jì)流限流:可以設(shè)計(jì)限流規(guī)則,記錄訪問流量路由:將請(qǐng)求進(jìn)行內(nèi)部(服務(wù))轉(zhuǎn)發(fā)#?2.2 API 網(wǎng)關(guān)的實(shí)現(xiàn)
業(yè)界常用的 API 網(wǎng)關(guān)有很多方式,如:Spring Cloud Zuul、 Nginx、Tyk、Kong。本篇介紹的對(duì)象正是?Spring Cloud Zuul。
Zuul 是 Netflix 公司開源的一個(gè) API 網(wǎng)關(guān)組件,提供了認(rèn)證、鑒權(quán)、限流、動(dòng)態(tài)路由、監(jiān)控、彈性、安全、負(fù)載均衡、協(xié)助單點(diǎn)壓測(cè)等邊緣服務(wù)的框架。
Spring Cloud Zuul 是基于 Netflix Zuul 的微服務(wù)路由和過濾器的解決方案,也用于實(shí)現(xiàn) API 網(wǎng)關(guān)。其中,路由功能負(fù)責(zé)將外部請(qǐng)求轉(zhuǎn)發(fā)到具體的微服務(wù)實(shí)例上,是實(shí)現(xiàn)外部訪問統(tǒng)一入門的基礎(chǔ)。而過濾功能是負(fù)責(zé)對(duì)請(qǐng)求的處理過程進(jìn)行干預(yù),是實(shí)現(xiàn)請(qǐng)求校驗(yàn)、服務(wù)聚合等功能的基礎(chǔ)。
Spring Cloud Zuul 和 Eureka 進(jìn)行整合時(shí),Zuul 將自身注冊(cè)到 Eureka 服務(wù)中,同時(shí)從 Eureka 中獲取其他微服務(wù)信息,以便請(qǐng)求可以準(zhǔn)確的通過 Zuul 轉(zhuǎn)發(fā)到具體微服務(wù)上。
三、實(shí)戰(zhàn)演練
本次測(cè)試案例基于之前發(fā)表的文章中介紹的案例進(jìn)行演示,不清楚的讀者請(qǐng)先轉(zhuǎn)移至?《Spring Cloud 入門 之 Hystrix 篇(四)》?進(jìn)行瀏覽。
當(dāng)前的項(xiàng)目列表如下:
| common-api | - | 公用的 api,如:實(shí)體類 |
| eureka-server | 9000 | 注冊(cè)中心(Eureka 服務(wù)端) |
| goods-server | 8081 | 商品服務(wù)(Eureka 客戶端) |
| goods-server-02 | 8082 | 商品服務(wù)(Eureka 客戶端) |
| goods-server-03 | 8083 | 商品服務(wù)(Eureka 客戶端) |
| order-server | 8100 | 訂單服務(wù)(Eureka 客戶端) |
創(chuàng)建一個(gè)為名 gateway-server 的 Spring Boot 項(xiàng)目。
#?3.1 添加依賴
<!-- eureka 客戶端 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency><!-- zuul 網(wǎng)關(guān) --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency>#?3.2 配置文件
server: port: 9600spring: application: name: gatewayeureka: instance: instance-id: gateway-9600 prefer-ip-address: true client: service-url: defaultZone: http://localhost:9000/eureka/ # 注冊(cè)中心訪問地址#?3.3 啟動(dòng) Zuul
在啟動(dòng)類上添加?@EnableZuulProxy?注解:
@EnableZuulProxy @SpringBootApplication public class GatewayApplication {public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }啟動(dòng)上邊的所有項(xiàng)目,打開 Postman 請(qǐng)求訂單下單接口,如下圖:
圖中,我們首先不經(jīng)過網(wǎng)關(guān)直接訪問 order-server 項(xiàng)目請(qǐng)求地址:http://localhost:8100/order/place
之后再修改成訪問 gateway-server 項(xiàng)目的請(qǐng)求地址:http://localhost:9600/order/order/place
最終,響應(yīng)結(jié)果都一樣。
提示:http://localhost:9600/order/order/place?中第一個(gè) order 表示的是注冊(cè)在 Eureka 上的訂單服務(wù)名稱。
#?3.4 zuul 常用配置
修改路由:
zuul: sensitive-headers: # 全局忽略敏感頭,即允許接收 cookie 等請(qǐng)求頭信息 routes: extlight: # 任意名字,保證唯一即可 path: /extlight/** # 自定義,真正用到的請(qǐng)求地址 service-id: ORDER # 路由到的目標(biāo)服務(wù)名稱將訂單服務(wù)的路由名稱改成 extlight。
使用 Postman 請(qǐng)求下單接口,運(yùn)行結(jié)果:
請(qǐng)求成功。
禁用路由:
zuul: ignored-patterns: - /order/order/**http://localhost:9600/order/order/place?無法被正常路由到訂單服務(wù),響應(yīng)返回 404。
路由加前綴:
zuul: prefix: /api所有請(qǐng)求中的 path 需要添加 api 前綴。如:?http://localhost:9600/extlight/order/place?需要改成?http://localhost:9600/api/extlight/order/place。
設(shè)置敏感頭:
zuul: sensitive-headers: # 設(shè)置全局敏感頭,如果為空,表示接收所有敏感頭信息或
zuul: routes: extlight: # 任意名字,保證唯一即可 path: /extlight/** # 自定義,真正用到的請(qǐng)求地址 service-id: ORDER # 路由到的目標(biāo)服務(wù)名稱 sensitive-headers: # 針對(duì) /extlight/ 的請(qǐng)求設(shè)置敏感頭信息四、Zuul 自定義過濾器
Zuul 的核心技術(shù)就是過濾器,該框架提供了 ZuulFilter 接口讓開發(fā)者可以自定義過濾規(guī)則。
我們以身份檢驗(yàn)為例,自定義 ZuulFilter 過濾器實(shí)現(xiàn)該功能。
#?4.1 創(chuàng)建用戶服務(wù)
新建名為 user-server 的項(xiàng)目。
添加依賴:
<!-- common api --> <dependency> <groupId>com.extlight.springcloud</groupId> <artifactId>common-api</artifactId> <version>${parent-version}</version> </dependency><!-- springmvc --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency><!-- eureka 客戶端 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>application.yml:
server: port: 8200spring: application: name: USEReureka: instance: instance-id: user-api-8200 prefer-ip-address: true # 訪問路徑可以顯示 IP client: service-url: defaultZone: http://localhost:9000/eureka/ # 注冊(cè)中心訪問地址登錄接口:
@RestController @RequestMapping("/user") public class LoginController {@PostMapping("/login") public Result login(String username, String password, HttpServletResponse response) {if ("admin".equals(username) && "admin".equals(password)) { // 模擬生成 token,實(shí)際開發(fā)中 token 應(yīng)存放在數(shù)據(jù)庫或緩存中 String token = "123456"; Cookie cookie = new Cookie("token", token); cookie.setPath("/"); cookie.setMaxAge(60 * 10); response.addCookie(cookie);return Result.success(); }return Result.fail(401, "賬號(hào)或密碼錯(cuò)誤"); } }user-server 啟動(dòng)類:
@EnableEurekaClient @SpringBootApplication public class UserServerApplication {public static void main(String[] args) { SpringApplication.run(UserServerApplication.class, args); } }#?4.2 創(chuàng)建 ZuulFilter 過濾器
在 gateway-server 項(xiàng)目中,新建一個(gè)過濾器,需要繼承?ZuulFilter 類:
@Component public class AuthenticationFilter extends ZuulFilter {/** * 是否開啟過濾 */ @Override public boolean shouldFilter() { RequestContext context = RequestContext.getCurrentContext(); HttpServletRequest request = context.getRequest();boolean flag = request.getRequestURI().contains("/login"); // 如果是登錄請(qǐng)求不進(jìn)行過濾 if (flag) { System.out.println("========不執(zhí)行 zuul 過濾方法======="); } else { System.out.println("========執(zhí)行 zuul 過濾方法======="); } return !flag; }/** * 過濾器執(zhí)行內(nèi)容 */ @Override public Object run() throws ZuulException {RequestContext context = RequestContext.getCurrentContext(); HttpServletRequest request = context.getRequest(); String token = request.getParameter("token"); // 此處模擬獲取數(shù)據(jù)庫或緩存中的 token String dbToken = "123456"; // 此處簡單檢驗(yàn) token if (token == null || "".equals(token) || !dbToken.equals(token)) { context.setSendZuulResponse(false); context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); }return null; }/** * 過濾器類型 */ @Override public String filterType() { return "pre"; }/** * 過濾器執(zhí)行順序 */ @Override public int filterOrder() { return 0; }}其中,filterType 有 4 種類型:
pre: 這種過濾器在請(qǐng)求被路由之前調(diào)用。我們可利用這種過濾器實(shí)現(xiàn)身份驗(yàn)證、在集群中選擇請(qǐng)求的微服務(wù)、記錄調(diào)試信息等。routing:這種過濾器將請(qǐng)求路由到微服務(wù)。這種過濾器用于構(gòu)建發(fā)送給微服務(wù)的請(qǐng)求,并使用 Apache HttpClient 或 Netfilx Ribbon 請(qǐng)求微服務(wù)。post:這種過濾器在路由到微服務(wù)以后執(zhí)行。這種過濾器可用來為響應(yīng)添加標(biāo)準(zhǔn)的 HTTP Header、收集統(tǒng)計(jì)信息和指標(biāo)、將響應(yīng)從微服務(wù)發(fā)送給客戶端等。error:在其他階段發(fā)生錯(cuò)誤時(shí)執(zhí)行該過濾器。其過濾順序如下圖:
#?4.3 測(cè)試過濾器
運(yùn)行所有項(xiàng)目,測(cè)試操作步驟如下:
請(qǐng)求用戶服務(wù)的登錄接口(http://localhost:9600/user/user/login),請(qǐng)求不執(zhí)行 zuul 過濾方法,并且請(qǐng)求響應(yīng)返回的 cookie 包含 token請(qǐng)求訂單服務(wù)的下單接口(http://localhost:9600/extlight/order/place),但不攜帶 token,請(qǐng)求需要執(zhí)行 zuul 過濾方法,請(qǐng)求響應(yīng) 401 權(quán)限不足請(qǐng)求訂單服務(wù)的下單接口(http://localhost:9600/extlight/order/place),攜帶之前登錄接口返回的 token,請(qǐng)求需要執(zhí)行 zuul 過濾方法,校驗(yàn)通過后路由到訂單服務(wù)執(zhí)行之后的操作測(cè)試效果圖如下:
五、案例源碼
Zuul demo 源碼
六、參考資料
Announcing Zuul: Edge Service in the Cloud
總結(jié)
以上是生活随笔為你收集整理的Spring Cloud 入门 之 Zuul 篇(五)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hihocoder #1329 : 平衡
- 下一篇: Spring Cloud 入门 之 Eu