系統自帶全局過濾器:
全局過濾器特點:
局部過濾器和全局過濾器區別:
局部:局部針對某個路由, 需要在路由中進行配置
全局:針對所有路由請求, 一旦定義就會投入使用
自定義全局過濾器:
實現 GlobalFiter 過濾器:
package com.tulingxueyuan.filters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; @Component public class LogFilter implements GlobalFilter { Logger log= LoggerFactory.getLogger(this.getClass()); @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { log.info(exchange.getRequest().getPath().value()); return chain.filter(exchange); } }
Gateway跨域配置:
第一種方式:
# 跨域配置 spring: cloud: gateway: globalcors: cors-configurations: '[/**]': # 允許跨域訪問的資源 allowedOrigins: "*" #跨域允許來源, * 代表允許所有的請求進行跨域請求 allowedMethods: - GET - POST
第二種方式:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.util.pattern.PathPatternParser; @Configuration public class CorsConfig { @Bean public CorsWebFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedMethod("*"); // 允許的method config.addAllowedOrigin("*"); // 允許的來源 config.addAllowedHeader("*"); // 允許的請求頭參數 // 運行訪問的資源 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }