spring?cloud?gateway中配置uri三種方式
spring cloud gateway中配置uri
gateway中配置uri配置有三種方式:
- websocket方式:uri: ws://localhost:9000
- http方式: uri: http://localhost:8130/
- lb注冊中心配置方式(注冊的服務名稱): uri: lb://monitor-ms
gateway的lb方式識別的服務名稱命名規(guī)則:
"[a-zA-Z]([a-zA-Z]|\\d|\\+|\\.|-)*:.*"
SpringCloud GateWay 使用說明
前言:
gateway 組件是SpringCloud 組件中的網(wǎng)關組件,主要是解決路由轉(zhuǎn)發(fā)的問題;跟nginx有點類似,區(qū)別是nginx多用在前端上,gateway用在后端上。當然gateway的功能不止路由轉(zhuǎn)發(fā),還可以用來:
1.針對所有請求做統(tǒng)一鑒權、限流、熔斷、日志;
2.協(xié)議轉(zhuǎn)化,針對后端多種協(xié)議可以在網(wǎng)關層統(tǒng)一處理后以http對外服務;
3.統(tǒng)一錯誤代碼處理(跟springboot統(tǒng)一錯誤處理配置一樣);
一、配置說明
gateway的配置文件是其使用的核心。
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Path=/table-service/** filters: - StripPrefix=1
字段說明:
id:自定義路由的ID;
uri:目標服務器地址,同時支持 URI(http://ip:port/route) 和 lb(lb://應用注冊服務名) 方式,推薦使用lb方式;
predicates:路由條件,根據(jù)匹配結果決定是否執(zhí)行該請求路由;
filters:過濾規(guī)則,包含 pre 和 post 過濾,其中 StripPrefix=1 表示根據(jù)請求時去掉URL路徑的第一個前綴。
二、路由條件配置說明
即predicates 配置項,支持多種規(guī)則:
1. 指定時間規(guī)則匹配路由
時間的書寫必須是ZoneDateTime格式。
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - After=2022-07-20T10:25:00.000+08:00[Asia/Shanghai]
有三種規(guī)則:
After:指定時間之后轉(zhuǎn)發(fā)到該服務;
Before:指定時間之前轉(zhuǎn)發(fā)到該服務;
Between:兩個時間之前轉(zhuǎn)發(fā)到該服務,兩個時間之間用逗號隔開;
2. Cookie 匹配路由
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Cookie=cho,123
上述配置表示請求時Cookie 必須攜帶 cho=123 鍵值對才能轉(zhuǎn)發(fā)到該服務;逗號前表示鍵值,逗號后表示該鍵對應的值,該值是個正則表達式。
3. Header 匹配路由
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Header=cho,123
上述配置表示請求時header 必須攜帶 cho=123 鍵值對才能轉(zhuǎn)發(fā)到該服務;逗號前表示鍵值,逗號后表示該鍵對應的值,該值是個正則表達式。
4. Host 匹配路由
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Host=127.0.0.1,localhost
上述配置表示請求時Host 必須攜帶 127.0.0.1,localhost 中的任何一個值才能轉(zhuǎn)發(fā)到該服務;匹配多值時用逗號隔開,并且支持星號(*)做域名通配符。
5. 請求方法匹配路由
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Method=POST,GET
上述配置表示請求時只有 GET 和 POST 方法才能轉(zhuǎn)發(fā)到該服務;匹配多值時用逗號隔開。
6. 請求路徑匹配路由
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Path=/table/**
該方式是使用最多的。/* 表示單層路徑匹配,/** 表示多層路徑匹配。
三、過濾配置說明
即filters 配置項,支持多種配置:
1. AddRequestParameters GatewayFilter Factory
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Path=/table/** filters: - AddRequestParameter=foo,bar
上述配置會對走該路由的所有請求都加上 foo=bar 參數(shù)。
2. AddResponseHeader GatewayFilter Factory
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Path=/table/** filters: - AddResponseHeader=foo,bar
上述配置會對走該路由的所有請求的返回都加上響應頭foo=bar 。
3. RequestRateLimiter GatewayFilter Factory
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Path=/table/** filters: - name: RequestRateLimiter args: redis-rate-limiter.replenishRate: 10 redis-rate-limiter.burstCapacity: 20
這個過濾器是基于令牌桶實現(xiàn)的,replenishRate 表示令牌填充速度,burstCapacity 表示令牌桶容量;限流用的,需要集成redis才行。限流的使用略復雜,建議單獨研究。
4. Retry GatewayFilter Factory
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Path=/table/** filters: - name: Retry args: retries: 3 status: 503
總共涉及4個參數(shù):
retries:重試次數(shù);
status:http 請求返回的狀態(tài)碼,上述配置表示服務端返回503時發(fā)起重試;
methods:指定請求類型才會發(fā)起重試;
series:配置錯誤碼段,表示符合狀態(tài)碼才發(fā)起重試,默認SERVER_ERROR(5),即 5xx 段狀態(tài)碼才會發(fā)起重試;如果 series 配置了錯誤碼,但 status 缺省,則仍然匹配 series 進行重試。
四、自定義 Filter
自定義 filter 有兩個,GlobalFilter 和 GatewayFilter ;GlobalFilter 對全局生效,GatewayFilter 只對配置了的才生效。
1. 自定義GlobalFilter
可以存在多個GlobalFilter,執(zhí)行順序由 getOrder() 控制,值越小執(zhí)行越靠前。
@Slf4j @Service public class GatewayGlobalFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); log.info("pre action..."); //請求到路由前的操作... return chain.filter(exchange).then(Mono.fromRunnable(() -> { log.info("post action..."); //請求返回后的操作... })); } @Override public int getOrder() { return 0; } }
2. 自定義 gatewayFilter
@Slf4j @Service public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomGatewayFilterFactory.CustomConfig> { public CustomGatewayFilterFactory() { super(CustomConfig.class); } @Override public GatewayFilter apply(CustomConfig config) { return ((exchange, chain) -> { String name = config.getName(); log.info("config name:{}", name); log.info("pre action..."); if (name.equals("123")) { // 使用config值的樣例 return exchange.getResponse().setComplete(); // 不返回任何信息 } return chain.filter(exchange).then(Mono.fromRunnable(() -> { log.info("post action..."); })); }); } public static class CustomConfig { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } }
上述對應的配置文件:
spring: cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Path=/table/** filters: - name: Custom args: name: 123
幾點注意:
1. 類名一般遵循以 GatewayFilterFactory 結尾,所以默認情況下過濾器 name 會采用該自定義類名的前綴,這里配置 name=Custom;或者類名完全不遵循上述規(guī)則,,配置時name為類全名;
2. 在 apply 方法中,同時包含 Pre 和 Post 過濾;在 then 方法中是請求執(zhí)行結束之后的處置;
3. CustomConfig 是一個配置類,其屬性值可在配置文件 args 下一層進行配置;
3. 補充
以下是請求不滿足條件時的json 返回。
// msg 是個 json 字符串 DataBuffer bodyDataBuffer =response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8)); return response.writeWith(Mono.just(bodyDataBuffer));
五、整個 demo
1. 本地起一個eureka的注冊中心(也可以用nacos等其他的注冊中心)
端口:9099
本片代碼不是該博客核心,忽略。
2. 起一個gateway的client注冊到eureka
依賴:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>eureka-gateway</artifactId> <version>1.0.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.5</version> <relativePath/> </parent> <dependencies> <!--在springboot的pom文件中,該依賴已經(jīng)集成了springMVC等web啟動器,不需要再添加spring-boot-starter-web 依賴了--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!--eureka-client依賴--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>2020.0.2</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> </project>
啟動類:
@EnableEurekaClient @SpringBootApplication public class GatewayServer { public static void main(String[] args) { SpringApplication.run(GatewayServer.class, args); } }
配置文件:
server: port: 8999 spring: application: name: gateway-service cloud: gateway: routes: - id: table-service uri: lb://table-service predicates: - Path=/table-service/** filters: - StripPrefix=1 - id: table-service uri: lb:ws://table-service #這是websocket轉(zhuǎn)發(fā)的配置 predicates: - Path=/table-socket/** filters: - StripPrefix=1 eureka: instance: lease-expiration-duration-in-seconds: 10 lease-renewal-interval-in-seconds: 5 prefer-ip-address: true instance-id: ${spring.cloud.client.ip-address}:${server.port} client: service-url: defaultZone: http://user:passwd@localhost:9099/eureka/
到此這篇關于spring cloud gateway中配置uri三種方式的文章就介紹到這了,更多相關spring cloud gateway配置uri內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Runtime.getRuntime().exec 路徑包含空格的解決
這篇文章主要介紹了Runtime.getRuntime().exec 路徑包含空格的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11迅速掌握Java容器中常用的ArrayList類與Vector類用法
這篇文章主要介紹了Java容器中常用的ArrayList類與Vector類用法,文中只對其最基本的功能給出了示例代碼,需要的朋友可以參考下2015-11-11Java線程池ThreadPoolExecutor原理及使用實例
這篇文章主要介紹了Java線程池ThreadPoolExecutor原理及使用實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-05-05