springcloud2 gateway 之一:簡單樣例
http://www.javashuo.com/article/p-nkplpein-np.htmljava
springcloud2 gateway 之二:轉發調用eureka客戶端服務
https://blog.csdn.net/haveqing/article/details/88427571react
文件結構web
1、GatewayConfig.javaspring
package com.urthink.upfs.springcloudgateway.config; import com.urthink.upfs.springcloudgateway.filter.TokenFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class GatewayConfig { @Bean public TokenFilter tokenFilter(){ return new TokenFilter(); } }
2、TokenFilter.java數據庫
每個GlobalFilter都做用在每個router上,可以知足大多數的需求。可是若是遇到業務上的定製,可能須要編寫知足本身需求的GlobalFilter。在下面的案例中將講述如何編寫本身GlobalFilter,該GlobalFilter會校驗請求中是否包含了請求參數「token」,如何不包含請求參數「token」則不轉發路由,不然執行正常的邏輯。代碼以下:架構
package com.urthink.upfs.springcloudgateway.filter; 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.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; /** * gateway全局過濾器 * https://blog.csdn.net/forezp/article/details/85057268 */ public class TokenFilter implements GlobalFilter, Ordered { Logger logger= LoggerFactory.getLogger( TokenFilter.class ); @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String token = exchange.getRequest().getQueryParams().getFirst("token"); if (token == null || token.isEmpty()) { logger.info( "token is empty..." ); exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); return exchange.getResponse().setComplete(); } return chain.filter(exchange); } @Override public int getOrder() { return -100; } }
在上面的TokenFilter須要實現GlobalFilter和Ordered接口,這和實現GatewayFilter很相似。而後根據ServerWebExchange獲取ServerHttpRequest,而後根據ServerHttpRequest中是否含有參數token,若是沒有則完成請求,終止轉發,不然執行正常的邏輯。app
3、訪問ide
http://localhost:8080/app2/demo/test1微服務
返回 401 Unauthorizedspa
http://localhost:8080/app2/demo/test1?token=tokendata
正常返回數據
既然gateway已經鏈接到eureka,就能夠經過feign調用其餘服務,作更復雜的權限驗證了,而沒必要直接連數據庫。
參考:
spring cloud gateway之filter篇
https://blog.csdn.net/forezp/article/details/85057268
Spring-Cloud-Gateway之過濾器GatewayFilter
https://www.jianshu.com/p/eb3a67291050
spring cloud gateway 2 深刻了解 - filter
https://www.jianshu.com/p/5e40bbc95eb9
微服務架構spring cloud - Gateway過濾器(十二)
https://blog.csdn.net/m0_37834471/article/details/82621337