Spring cloud alibaba之Gateway網(wǎng)關功能特征詳解
1.網(wǎng)關簡介
所謂的網(wǎng)關就是指系統(tǒng)的統(tǒng)一入口,它封裝了運用程序的內(nèi)部結構,為客戶端提供統(tǒng)一的服務,一些與業(yè)務功能無關的公共邏輯可以在這里實現(xiàn),諸如認證、鑒權、監(jiān)控、路由轉發(fā)等。
2.什么是spring cloud gateway
網(wǎng)關作為流量的入口,常用的功能包括路由轉發(fā)、權限校驗、限流等。
spring cloud gateway是spring cloud推出的第二代網(wǎng)關,是由WebFlux+Netty+Reactor實現(xiàn)的響應式的API網(wǎng)關,它不能在傳統(tǒng)的servlet容器中工作,也不能構建成war包;旨在為微服務提供一種簡單且有效的API路由的管理方式,并基于Filter的方式提供網(wǎng)關的基本功能,例如安全認證、監(jiān)控、限流等。
spring cloud gateway功能特性:
(1)基于spring Framework5、Project Reactor和spring boot 2.0進行構建
(2)動態(tài)路由:能夠匹配任何請求屬性
(3)支持路徑重寫
(4)集成spring cloud服務發(fā)現(xiàn)功能(nacos)
(5)可集成流控級功能(sentinel)
(6)可以對路由指定易于編寫的Predicate(斷言)、Filter(過濾器)
2.1核心概念
路由(Route):
路由是網(wǎng)關中最重要的部分,路由信息包括一個ID、一個目的URL、一組斷言工廠、一組Filter組成。如果斷言為真,則說明請求的URL和配置的路由匹配。
斷言(Predicate):
java8中的斷言函數(shù),spring cloud gateway中的斷言函數(shù)類型是spring 5.0框架中的ServerWebExchange。斷言函數(shù)運行開發(fā)者去定義匹配Http request中的任何信息,比如請求頭和參數(shù)。
過濾器(Filter):
分為Gateway filter和Global filter,F(xiàn)ilter可以對請求和響應進行處理。
3.Spring Cloud Gateway快速開始
(1)創(chuàng)建maven工程

(2)pom.xml中導入需要的依賴
<!-- gateway依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>3.0.1</version>
</dependency>
(3)application.properties中配置路由斷言和過濾器
server.port=8086 spring.application.name=api-gateway #gateway配置 #網(wǎng)關唯一標識,路由到order,routes是集合,使用數(shù)組索引來設置 spring.cloud.gateway.routes[0].id=order_route #需要轉發(fā)的地址 spring.cloud.gateway.routes[0].uri=http://localhost:8084 #斷言規(guī)則,predicates也是一個集合,http://localhost:8086/order-serv/order/add 路由到 #http://localhost:8085/order-serv/order/add spring.cloud.gateway.routes[0].predicates[0]=Path=/order-serv/** #過濾器,轉發(fā)之前去掉第一層路徑:http://localhost:8085/order/add spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1
(4)瀏覽器中訪問網(wǎng)關配置的地址,可以路由到我們配置服務器地址
4.Gateway
整合Nacos
在配置文件中寫死的轉發(fā)地址,會存在很多問題,我們需要集成nacos,從注冊中心中獲取此地址
(1)pom.xml中添加nacos的依賴
<!-- Nacos服務注冊發(fā)現(xiàn)-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
(2)application.properties中配置nacos連接信息
#nacos服務連接地址 spring.cloud.nacos.server-addr=127.0.0.1:8848 #nacos discovery連接用戶名 spring.cloud.nacos.discovery.username=nacos #nacos discovery連接密碼 spring.cloud.nacos.discovery.password=nacos #nacos discovery工作空間 spring.cloud.nacos.discovery.workspace=public
(3)application.properties中配置路由的uri為需要訪問的服務名,前綴lb(loadBalance負載均衡)

對應需要訪問的order服務

此時nacos中是有order-service服務的

(4)重啟服務,是可以路由到我們的order服務的

(5)簡寫:去掉關于路由的配置,自動尋找服務,根據(jù)訪問的地址,自動從nacos中找到服務進行路由。application.properties中配置
#自動識別nacos服務,默認是關閉的,開啟后會根據(jù)訪問的地址http://localhost:8086/order-service/order/add #自動路由到order-service服務上 spring.cloud.gateway.discovery.locator.enabled=true
注釋了其它路由的配置

自動尋找服務也是可以正常訪問服務

5.路由斷言工廠(Route Predicate Factories)配置
作用:當請求gateway的時候,使用斷言對請求進行匹配,如果匹配成功就路由轉發(fā),匹配不成功返回404
類型:內(nèi)置
官網(wǎng)參考地址:https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-request-predicates-factories
SpringCloud Gateway包括許多內(nèi)置的斷言工廠,所有這些斷言都與HTTP請求的不同屬性匹配。
(1)基于DateTime類型的斷言工廠
此類型的斷言工廠根據(jù)時間做判斷,主要有三個:
AfterRoutePredicateFactory:接收一個日期參數(shù),判斷請求日期是否晚于指定日期。
BeforeRoutePredicateFactory:接收一個日期參數(shù),判斷請求日期是否早于指定日期
BetweenRoutePredicateFactory:接收兩個日期參數(shù),判斷請求日期是否在指定時間段內(nèi)
- After=2019-12-31T23:59:59.789+08:00[Asia/Shanghai]
路由規(guī)則改為當前時間之后

系統(tǒng)訪問404

日期改為當前日期之前

服務正常訪問

(2)基于遠程地址的斷言工廠
RemoteAddrRoutePredicateFactory:接收一個IP地址段,判斷請求主機地址是否在地址段中
- RemoteAddr=192.168.1.1/24
(3)基于Cookie的斷言工廠
CookieRoutePredicateFactory:接收兩個參數(shù),cookie名字和一個正則表達式,判斷cookie是否具有給定名稱且值與正則表達式匹配。
-Cookie=chocolate,ch.
(4)基于Header的斷言工廠
HeaderRoutePredicateFactory:接收兩個參數(shù),標題名稱和正則表達式,判斷請求Header是否具有給定名稱值與正則表達式匹配。
-Header=X-Request-Id,\d+
(5)基于Host的斷言工廠
HostRoutePredicateFactory:接收一個參數(shù),主機名模式,判斷請求的Host是否滿足匹配規(guī)則。
-Host=**.testhost.org
(6)基于Method請求方法的斷言工廠
MethodRoutePredicateFactory:接收一個參數(shù),判斷請求類型是否跟指定的類型匹配
-Method=GET
(7)基于Path請求路徑的斷言工廠
PathRoutePredicateFactory:接收一個參數(shù),判斷請求的URI部分是否滿足路徑規(guī)則
-Path=/foo/{segment}
(8)基于Query請求參數(shù)的斷言工廠
QueryRoutePredicateFactory:接收兩個參數(shù),請求param和正則表達式,判斷請求參數(shù)是否具有給定個名稱且值與正則表達式匹配
-Query=baz,ba.
(9)基于路由權重的斷言工廠
WeightRoutePredicateFactory:接收一個[組名,權重],然后對于同一個組內(nèi)的路由按照權重轉發(fā)
spring:
cloud:
gateway:
routes:
- id: weight_high
uri: https://weighthigh.org
predicates:
- Weight=group1, 8
- id: weight_low
uri: https://weightlow.org
predicates:
- Weight=group1, 2
6.自定義路由斷言工廠
自定義路由斷言工廠需要繼承AbstractRoutePredicateFactory類,重寫apply的方法邏輯,在apply方法中通過exchange.getRequest()拿到ServerHttpRequest對象,從而可以獲取到請求的參數(shù)、請求方式、請求頭等信息
注意:
類的命名需要以RoutePredicateFactory結尾;
必須使用spring的bean加載到容器中;
必須繼承AbstractRoutePredicateFactory;
必須聲明靜態(tài)內(nèi)部類,聲明屬性來接收配置文件中對應的斷言信息;
需要結合shortcutFieldOrder進行綁定;
通過apply進行邏輯判斷,true就是匹配成功,false則匹配失敗
(1)創(chuàng)建一個類CheckAuthRoutePredicateFactory,里面的處理代碼,可以直接復制一份
QueryRoutePredicateFactory邏輯代碼

package com.qingyun.predicate;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;
import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;
import javax.validation.constraints.NotEmpty;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;
/**
* 自定義斷言工廠
*/
@Component
public class CheckAuthRoutePredicateFactory extends AbstractRoutePredicateFactory<CheckAuthRoutePredicateFactory.Config> {
public static final String PARAM_KEY = "param";
public static final String REGEXP_KEY = "regexp";
public CheckAuthRoutePredicateFactory() {
super(CheckAuthRoutePredicateFactory.Config.class);
}
public List<String> shortcutFieldOrder() {
return Arrays.asList("param", "regexp");
}
public Predicate<ServerWebExchange> apply(CheckAuthRoutePredicateFactory.Config config) {
return new GatewayPredicate() {
public boolean test(ServerWebExchange exchange) {
if (!StringUtils.hasText(config.regexp)) {
return exchange.getRequest().getQueryParams().containsKey(config.param);
} else {
List<String> values = (List)exchange.getRequest().getQueryParams().get(config.param);
if (values == null) {
return false;
} else {
Iterator var3 = values.iterator();
String value;
do {
if (!var3.hasNext()) {
return false;
}
value = (String)var3.next();
} while(value == null || !value.matches(config.regexp));
return true;
}
}
}
public String toString() {
return String.format("Query: param=%s regexp=%s", config.getParam(), config.getRegexp());
}
};
}
@Validated
public static class Config {
@NotEmpty
private String param;
private String regexp;
public Config() {
}
public String getParam() {
return this.param;
}
public CheckAuthRoutePredicateFactory.Config setParam(String param) {
this.param = param;
return this;
}
public String getRegexp() {
return this.regexp;
}
public CheckAuthRoutePredicateFactory.Config setRegexp(String regexp) {
this.regexp = regexp;
return this;
}
}
}
(2)自定義的斷言類名為CheckAuthRoutePredicateFactory,所以application.properties中使用CheckAuth作為斷言規(guī)則配置

(3)修改CheckAuthRoutePredicateFactory類,定義靜態(tài)類Config的字段,添加get和set方法,可以接收到application.properties中配置的CheckAuth的值

(4)結合中shortcutFieldOrder使用,添加name屬性到集合中

(5)apply方法中獲取Config中的name值,進行判斷匹配,返回true或false
(6)訪問系統(tǒng)可以正常訪問

(7)當改了application.properties中的CheckAuth值后,訪問不到服務


(8)完整自定義CheckAuthRoutePredicateFactory代碼
package com.qingyun.predicate;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;
import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;
import javax.validation.constraints.NotEmpty;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;
/**
* 自定義斷言工廠
*/
@Component
public class CheckAuthRoutePredicateFactory extends AbstractRoutePredicateFactory<CheckAuthRoutePredicateFactory.Config> {
public CheckAuthRoutePredicateFactory() {
super(CheckAuthRoutePredicateFactory.Config.class);
}
public List<String> shortcutFieldOrder() {
return Arrays.asList("name");
}
public Predicate<ServerWebExchange> apply(CheckAuthRoutePredicateFactory.Config config) {
return new GatewayPredicate() {
public boolean test(ServerWebExchange exchange) {
if(config.getName().equals("qingyun")){
return true;
}
return false;
}
};
}
@Validated
public static class Config {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
7.Filter過濾器
官網(wǎng)參考:https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gatewayfilter-factories

(1)添加請求頭AddRequestHeader

被調(diào)用接口中接收參數(shù)

參數(shù)傳遞成功

(2)為路由轉發(fā)添加前綴PrefixPath

被調(diào)用服務需要配置context-path服務前綴

(3)RedirectTo重定向到其他服務,訪問接口后跳轉到配置的服務地址

8.自定義過濾器
注意:
類的命名需要以GatewayFilterFactory結尾;
必須使用spring的bean加載到容器中;
必須繼承AbstractNameValueGatewayFilterFactory;
必須聲明靜態(tài)內(nèi)部類,聲明屬性來接收配置文件中對應的斷言信息;
需要結合shortcutFieldOrder進行綁定;
通過apply進行邏輯判斷
(1)創(chuàng)建一個類CheckAuthGatewayFilterFactory,里面的處理代碼,可以直接復制一份
RedirectToGatewayFilterFactory邏輯代碼
(2)自定義的斷言類名為CheckAuthGatewayFilterFactory,所以application.properties中使用CheckAuth作為過濾器配置

(3)修改CheckAuthGatewayFilterFactory類,定義靜態(tài)類Config的字段,添加get和set方法,可以接收到application.properties中配置的CheckAuth的值

(4)結合中shortcutFieldOrder使用,添加value屬性到集合中

(5)apply方法中獲取Config中的value值,進行判斷匹配,繼續(xù)執(zhí)行或者返回404狀態(tài)
(6)不帶參數(shù)或者帶的參數(shù)不匹配時,訪問不到系統(tǒng)

(7)當參數(shù)與application.properties中的CheckAuth匹配后,正常訪問服務

(8)完整自定義CheckAuthGatewayFilterFactory代碼
package com.qingyun.filter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.RedirectToGatewayFilterFactory;
import org.springframework.cloud.gateway.support.HttpStatusHolder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import static org.springframework.cloud.gateway.support.GatewayToStringStyler.filterToStringCreator;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.setResponseStatus;
@Component
public class CheckAuthGatewayFilterFactory extends AbstractGatewayFilterFactory<CheckAuthGatewayFilterFactory.Config> {
public CheckAuthGatewayFilterFactory() {
super(CheckAuthGatewayFilterFactory.Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList("value");
}
@Override
public GatewayFilter apply(Config config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange,
GatewayFilterChain chain) {
//獲取到請求的參數(shù)值
String name = exchange.getRequest().getQueryParams().getFirst("name");
if(config.getValue().equals(name)){ //參數(shù)name的值等于配置的值
return chain.filter(exchange); //正常訪問服務
}else{ //直接返回404
exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND); //設置狀態(tài)碼
return exchange.getResponse().setComplete(); //設置結束訪問
}
}
};
}
public static class Config {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
9.自定義全局過濾器(Global Filters)
局部過濾器和全局過濾器區(qū)別:
局部:局部針對某個路由,需要在路由中進行配置
全局:針對所有路由請求,一旦配置就會投入使用
實現(xiàn)GlobalFilter接口,重寫filter方法
/**
* 全局過濾器
*/
@Component
public class GlobalLogFilter 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);
}
}
當訪問接口時,全局過濾器攔截到請求信息

10.Gateway跨域配置(CORS Configuration)
官網(wǎng)參考:https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#cors-configuration
跨域請求錯誤提示信息:在63342端口的頁面調(diào)用8086端口的后臺,出現(xiàn)跨域

在application.properties中配置:
#配置跨域允許(端口1的頁面調(diào)用端口2的后臺,出現(xiàn)跨域) #允許跨域訪問的資源:[/**] allowed-origins:跨域允許來源 spring.cloud.gateway.globalcors.cors-configurations.[/**].allowed-origins=* #跨域允許的請求方法(GET/POST...) spring.cloud.gateway.globalcors.cors-configurations.[/**].allowed-methods=* spring.cloud.gateway.globalcors.cors-configurations.[/**].allowed-headers=* spring.cloud.gateway.globalcors.cors-configurations.[/**].allow-credentials=true
寫配置類允許跨域:
/**
* 配置跨域
*/
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsFilter(){
//配置允許的設置
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
//配置添加到資源中
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",config);
return new CorsWebFilter(source);
}
}
配置跨域后請求成功:

11.Gateway整合Sentinel進行流控
網(wǎng)關作為內(nèi)部系統(tǒng)外的一層屏障,對內(nèi)起到一定的保護作用,限流便是其中之一。網(wǎng)關層的限流可以針對不同路由進行限流,也可以針對接口進行限流,或者根據(jù)接口的特征進行分組限流。
(1)pom.xml中添加依賴
<!--sentinel整合gateway-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
<!--sentinel依賴-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
(2)application.properties中添加sentinel控制臺連接
#整合sentinel控制臺 spring.cloud.sentinel.transport.dashboard=127.0.0.1:8090
(3)重啟服務,啟動sentinel控制臺服務,訪問接口,打開sentinel控制臺,可以看到sentinel為gateway單獨開放不同的菜單

(4)針對order_route進行流控設置

(5)快速訪問網(wǎng)關服務,達到設置的qps后,出現(xiàn)流控

12.流控配置說明

(1)API類型:RouteId和Api分組
RouteId對應application.properties中配置的id

Api分組可以在API管理處添加具有相同屬性控制的分組

在流控管理頁面添加設置,此流控設置將會對這組中設置的接口都有流控效果

(2)針對請求屬性設置
可以設置ip、請求頭等信息,匹配模式有精確、子串(結尾匹配)、正則表達式

13.自定義重寫流控返回信息
默認的流控返回信息不太友好

通過GatewayCallbackManager自定義流控信息
/**
* 自定義流控返回信息
*/
@Configuration
public class GatewayConfig {
@PostConstruct
public void init(){
BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("code", HttpStatus.TOO_MANY_REQUESTS);
map.put("message","被流控了");
return ServerResponse.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(map));
}
};
GatewayCallbackManager.setBlockHandler(blockRequestHandler);
}
}
此時在訪問接口,被流控后返回自定義的流控信息

到此這篇關于Spring cloud alibaba之Gateway網(wǎng)關功能特征詳解的文章就介紹到這了,更多相關Spring cloud alibaba內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Springboot集成MongoDB無認證與開啟認證的配置方式
本文主要介紹了Springboot集成MongoDB無認證與開啟認證的配置方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-03-03
SpringBoot基于Redis的分布式鎖實現(xiàn)過程記錄
Redis是一套 key-value 高性能數(shù)據(jù)庫,使用它可以大大提高我們的開發(fā)效率,在SpringBoot中,自動配置也幫我們節(jié)約了大量的配置,下面這篇文章主要給大家介紹了關于SpringBoot基于Redis的分布式鎖實現(xiàn)的相關資料,需要的朋友可以參考下2022-01-01

