Hello你們好,我是初晨,本章咱們學習SpringCloud 服務網關Zuul的使用。你們有問題和意見能夠發郵箱mr_beany@163.com
Zuul是Spring Cloud服務系列中的微服務API網關。java
Zuul的核心是一系列的filters, 其做用能夠類比Servlet框架的Filter,或者AOP。
git
全部的請求都會通過Zuul的驗證以後到達其餘各個服務。做爲一個邊界性質的應用程序,Zuul提供了動態路由、監控、彈性負載和安全功能。Zuul底層利用各類filter實現以下功能:web
1:建立過程與 SpringCloud 實戰二:Client的建立和高可用 同樣
spring
2:打開pom文件,添加依賴bootstrap
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>複製代碼
3:修改啓動類,添加@EnableZuulProxy後端
4:修改配置文件名稱爲bootstrap.ymlapi
spring:
application:
name: api-gateway
cloud:
config:
discovery:
enabled: true
service-id: CONFIG
profile: dev複製代碼
5:打開git倉庫,建立配置文件安全
6:啓動服務,訪問http://localhost:8761/
bash
能夠看到網關服務已經註冊成功。app
7:經過網關服務的路由來訪問其餘服務接口
咱們來訪問前面爲建立組件間通訊建立的http://localhost:8081/getServerResult
能夠訪問,再經過網關訪問http://localhost:8085/client/getServerResult
其中8085是服務網關的ip,client表明着client服務,getServerResult表明訪問路徑
8:自定義路由
經過Zuul每次訪問client服務時都須要帶上client,那麼怎麼才能不使用client而使用自定義的名稱呢?
修改api-gateway服務配置文件,添加以下配置
zuul:
routes:
myClient:
path: /myClient/**
serviceId: client複製代碼
這時地址欄中輸入http://localhost:8085/myClient/getServerResult
仍然能夠獲取到返回結果。
那麼咱們怎麼查看全部路由的規則呢?
地址欄中輸入http://localhost:8085/actuator/routes
9:禁用路由
修改api-gateway配置文件,添加以下
zuul:
ignored-patterns:
- /**/getServerResult複製代碼
此時咱們git上的配置文件應該爲
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
management:
endpoints:
web:
exposure:
include: '*'
zuul:
routes:
myClient:
path: /myClient/**
serviceId: client
# 設置能夠傳遞請求頭
sensitiveHeaders:
ignored-patterns:
- /**/getServerResult複製代碼
這裏咱們把這個url給禁用掉,再次訪問該地址
10:動態配置路由
利用咱們上篇文章講的統一配置中心,來實現動態配置路由功能,你們能夠先回想一下配置的步驟
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>複製代碼
spring:
rabbitmq:
host: 192.168.99.100
username: user
password: password
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
management:
endpoints:
web:
exposure:
include: '*'
zuul:
routes:
myClient:
path: /myClient/**
serviceId: client
# 設置能夠傳遞請求頭
sensitiveHeaders:
ignored-patterns:
- /**/getServerResult複製代碼
package com.example.apigateway;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
@Component
public class ZuulConfig {
@ConfigurationProperties("zuul")
@RefreshScope
public ZuulProperties zuulProperties(){
return new ZuulProperties();
}
}複製代碼
注意這時咱們訪問http://localhost:8085/myClient/getServerResult
是404的,由於咱們已經在配置文件中把url禁用了
修改git上api-gateway的配置文件,把禁用http://localhost:8085/myClient/getServerResult
的配置註釋掉
而後postman訪問http://localhost:8084/actuator/bus-refresh
來刷新配置文件
再次訪問