Zuul(Router and Filter)
WIKI: 傳送門
作用
- 認證,鑒權(Authentication/Security)
- 預判(Insights)
- 壓力測試(Stress Testing)
- 灰度/金絲雀測試(Canary Testing)
- 動態路由(Dynamic Routing)
- 服務遷移(Service Migration)
- 降低負載(Load Shedding)
- 靜態響應處理(Static Response handling)
- 主動/主動交換管理(Active/Active traffic management)
關鍵配置:
The configuration property
zuul.host.maxTotalConnections
andzuul.host.maxPerRouteConnections
, which default to 200 and 20 respectively.
創建mscx-ad-zuul
三步曲創建法:
添加依賴
<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>
加注解
@SpringCloudApplication
@EnableZuulProxy //啟用網關
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
改配置
spring:
application:
name: ad-gateway-zuul
server:
port: 1111
eureka:
client:
service-url:
defaultZone: http://server1:7777/eureka/,http://server2:8888/eureka/,http://server3:9999/eureka/
instance:
hostname: ad-gateway-zuul
zuul:
ignored-services: '*' # 過濾所有請求,除了下面routes中聲明過的服務
routes:
sponsor: #在路由中自定義服務路由名稱
path: /ad-sponsor/**
serviceId: mscx-ad-sponsor #微服務name
strip-prefix: false
search: #在路由中自定義服務路由名稱
path: /ad-search/**
serviceId: mscx-ad-search #微服務name
strip-prefix: false
prefix: /gateway/api
strip-prefix: false #不對 prefix: /gateway/api 設置的路徑進行截取,默認轉發會截取掉配置的前綴
過濾器編寫
我們來編寫一個記錄請求時間周期的過濾器,根據Filter的三種類型:Pre filters
,routing filters
和Post filters
,我們需要定義2個filter,用來記錄開始和結束時間,很明顯,我們需要實現Pre
& Post
2個過濾器。
@Slf4j
@Component
public class PreRequestFilter extends ZuulFilter {
@Override
public String filterType() {
// pre filter
return FilterConstants.PRE_TYPE;
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
//獲取當前請求的請求上下文
RequestContext requestContext = RequestContext.getCurrentContext();
//記錄請求進入時間
requestContext.set("api_request_time", System.currentTimeMillis());
return null;
}
}
---
@Slf4j
@Component
public class AccessLogFilter extends ZuulFilter {
@Override
public String filterType() {
return FilterConstants.POST_TYPE;
}
@Override
public int filterOrder() {
//需要最后一個執行的filter
return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
RequestContext requestContext = RequestContext.getCurrentContext();
HttpServletRequest request = requestContext.getRequest();
log.info("Request \"{}\" spent : {} seconds.", request.getRequestURI(),
(System.currentTimeMillis() - Long.valueOf(requestContext.get("api_request_time").toString())) / 1000);
return null;
}
}
Gateway
后續更新---
做一個好人。