概述
全局過濾器作用于所有的路由痴荐,不需要單獨配置,我們可以用它來實現(xiàn)很多統(tǒng)一化處理的業(yè)務需求官册,比如權限認證生兆,IP 訪問限制等等。
The GlobalFilter interface has the same signature as GatewayFilter. These are special filters that are conditionally applied to all routes. (This interface and usage are subject to change in future milestones).
聲明周期
Spring Cloud Gateway 基于 Project Reactor 和 WebFlux膝宁,采用響應式編程風格鸦难,打開它的 Filter 的接口 GlobalFilter 你會發(fā)現(xiàn)它只有一個方法 filter栖榨。
創(chuàng)建全局過濾器
實現(xiàn) GlobalFilter, Ordered
接口并在類上增加 @Component
注解就可以使用過濾功能了,非常簡單方便
AuthFilter
package com.wj.hello.spring.cloud.gateway.filters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Map;
/**
* 鑒權過濾器(全局過濾器)
*/
@Component // 向Spring聲明
public class AuthFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getQueryParams().getFirst("token");
if (token == null || token.isEmpty()) {
ServerHttpResponse response = exchange.getResponse();
// 封裝錯誤信息
Map<String, Object> responseData = Maps.newHashMap();
responseData.put("code", 401);
responseData.put("message", "非法請求");
responseData.put("cause", "Token is empty");
try {
// 將信息轉換為 JSON
ObjectMapper objectMapper = new ObjectMapper();
byte[] data = objectMapper.writeValueAsBytes(responseData);
// 輸出錯誤信息到頁面
DataBuffer buffer = response.bufferFactory().wrap(data);
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
return response.writeWith(Mono.just(buffer));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
return chain.filter(exchange);
}
/**
* 設置過濾器的執(zhí)行順序明刷,數(shù)字越小婴栽,級別越高
* @return
*/
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
測試過濾器
瀏覽器訪問:http://localhost:9000/nacos-consumer/echo/app/name 網(wǎng)頁顯示
瀏覽器訪問:http://localhost:9000/nacos-consumer/echo/app/name?token=123456 網(wǎng)頁顯示
Hello Nacos Discovery nacos-consumer i am from port 8081
更多的路由規(guī)則可查看官網(wǎng)
Global Filters:全局過濾
GatewayFilter:局部過濾