Zuul的主要功能是路由轉發和過濾器。客戶端請求通過路由網關調用相應的服務。這樣客戶端只需要和網關交互,而無需直接調用特定微服務的接口,而且方便監控,易於認證,減少客戶端和各個微服務之間的交互次數。
實現Zuul的方式如下:
1. 配置pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
這裏我們引入Eureka,需要將zuul註冊到註冊中心上去這樣才能拉取服務列表。
2. 創建啓動類
啓動類上需要添加@EnableZuulProxy
@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class ZuulApplication3001 {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication3001.class, args);
}
}
3. 增加配置文件
server:
port: 3001
eureka:
instance:
preferIpAddress:true
client:
serviceUrl:
defaultZone: http://localhost:7001/eureka/
spring:
application:
name: Zuul3001
zuul:
prefix: /nikola
routes:
ribbon:
path: /ribbonClass/**
serviceId: GateView8001
feign:
path: /feignClass/**
serviceId: GateView8001
路由規則爲前綴爲/nikola
。serviceId對應註冊到Eureka的服務實例名。path爲訪問該服務的請求路徑。
3. 測試
在瀏覽器中輸入:http://localhost:3001/nikola/feignClass/class; 回車顯示
[{“id”:1,“classcode”:“001”,“classname”:“class1”,“description”:“good class”,“operator”:“admin”,“makedate”:1557759681000,“modifydate”:1557759681000,“bak1”:null,“bak2”:null,“bak3”:null,“bak4”:null,“bak5”:null}]