Spring Cloud(四):路由閘道器Zuul
阿新 • • 發佈:2019-01-05
Zuul作為路由閘道器元件,在微服務架構當中有著非常重要的作用,主要體現在6個方面:
- Zuul,Ribbon以及Eureka相結合,可以實現智慧路由和負載均衡的功能,Zuul能夠將請求流量按某種策略分發到叢集狀態的多個伺服器例項。
- 閘道器將所有服務的API介面統一聚合,並統一對外暴露。外界系統呼叫API介面時,都是由閘道器對外暴露的API介面,外界系統不需要知道微服務系統當中各服務相互呼叫的複雜性。也保護了內部微服務單元的API介面,防止外界直接呼叫,導致服務的敏感資訊對外暴露。
- 閘道器服務可以做使用者身份認證和許可權驗證,防止非法請求操作API介面,對伺服器起到保護作用。
- 閘道器可以實現監控功能,實時日誌輸出,對請求進行記錄。
- 閘道器可以實現流量監控,在高流量的情況下,對伺服器進行降級。
- API介面從內部服務分離出來,方便做測試。
案例:基於上一篇文章的專案體系。
建立新的子模組(module):cloud-zuul
pom檔案:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>cloud-demo</artifactId> <groupId>spring-cloud-demo</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>cloud-zuul</artifactId> <name>cloud-zuul</name> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies> </project>
application.yml:配置路由等資訊
server: port: 8092 eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ spring: application: name: cloud-zuul zuul: routes: ribbon: path: /ribbon/** serviceId: service-consumer feign: path: /feign/** serviceId: client-feign
啟動類:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
測試:開啟所有相關服務,訪問:
該連結會根據路由配置的資訊找到對應的服務進行呼叫。