SpringCloud-API服務閘道器Zuul
SpringCloud微服務就是把一個大的專案拆分成多個小的模組,然後模組之間通過遠端呼叫、服務治理的技術互相配合工作,隨著業務的增加,專案也將會越來越龐大,介面數量也隨之增加,對外提供服務的介面也會增加,運維人員對於這些介面的管理也會變得越來越難。另一方面對於一個系統來說,許可權管理也是一個不可少的模組,在微服務架構中,系統被拆分,不可能每個模組都去新增一個個許可權管理,這樣系統程式碼重複、工作量大、後期維護也難。為了解決這些常見的架構問題,API閘道器應運而生。SpringCloudZuul是基於Netflix Zuul實現的API閘道器元件,它實現了請求路由、負載均衡、校驗過濾、與服務治理框架的結合、請求轉發是的熔斷機制和服務的聚合等功能。
簡單使用
新建一個SpringBoot專案,命名為api-gateway。新增如下依賴。
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency>
在主類上使用@EnableZuulProxy
註解開啟API閘道器服務功能
@SpringBootApplication
@EnableZuulProxy
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
配置檔案
server.port=8082 spring.application.name=api-gateway eureka.client.service-url.defaultZone=http://localhost:8080/eureka/ #這裡的配置是指,訪問/myZuul/**,請求會轉發到名稱為zuul-client這個微服務,也可以這樣zuul.routes.zuul-client=/myZuul/** zuul.routes.myZuul.path=/myZuul/** zuul.routes.myZuul.service-id=zuul-client #設定不過濾cookies zuul.routes.myZuul.sensitive-headers= #排除某些路由,這樣就可以禁止某些介面通過閘道器訪問。如果是.yml,- /myZuul/index2 zuul.ignored-patterns=/myZuul/index2
新建一個SpringBoot專案,命名為zuul-client。新增如下依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
啟動類
@SpringBootApplication
@EnableDiscoveryClient
public class ZuulClientApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulClientApplication.class, args);
}
}
配置檔案
server.port=8081
spring.application.name=zuul-client
#指定服務註冊中心的地址,這樣才能將我們的應用註冊到服務註冊中心
eureka.client.serviceUrl.defaultZone: http://localhost:8080/eureka/
新建一個Controller,裡面寫兩個介面
@RestController
public class Controller {
@GetMapping("/index1")
public String index1(HttpServletRequest request){
return "zuul-client index1";
}
@GetMapping("/index2")
public String index2(){
return "zuul-client index2";
}
}
啟動api-gateway和zuul-client將這兩個服務註冊到eureka。
我們在zuul-client寫了兩個介面,以/index1為例:
有了服務閘道器之後,我們可以通過以下方式來訪問/index
(1)通過自身地址來訪問:http://localhost:8081/index1
(2)通過服務閘道器來訪問:http://localhost:8082/zuul-client/index1
(3)由第二種方法可以知道,通過服務閘道器來訪問其它服務的介面,需要在地址中加上服務名稱。這裡要介紹的就是我們可以可以自定義服務名稱,方法看api-gateway中的配置檔案:
zuul.routes.myZuul.path=/myZuul/**
zuul.routes.myZuul.service-id=zuul-client
因此我們可以這樣來訪問:http://localhost:8082/myZuul/index1