前言
在使用Spring cloud Gateway (scg)時(shí),通過(guò)service name 全局匹配,路由到相應(yīng)的服務(wù)。但是請(qǐng)求/響應(yīng)超時(shí)怎么設(shè)置呢?
Spring cloud Gateway 超時(shí)設(shè)置
Spring cloud Gateway 可以為所有路由配置 Http 超時(shí)(響應(yīng)和連接),并為每個(gè)特定路由覆蓋。
http全局超時(shí)設(shè)置
-
connect-timeout連接超時(shí)必須以毫秒為單位指定。 -
response-timeout響應(yīng)超時(shí)必須指定為 java.time.Duration
spring:
cloud:
gateway:
httpclient:
connect-timeout: 200
response-timeout: 10s
然而,有些比較特殊接口,200ms是沒(méi)法滿足需求的,比如一個(gè)大文件上傳或下載,都會(huì)超過(guò)200ms,那怎么配置才能對(duì)這些特殊接口做單獨(dú)設(shè)置呢?
每個(gè)路由超時(shí)設(shè)置
配置每個(gè)路由超時(shí):
- 連接超時(shí)必須以毫秒為單位指定。
- 必須以毫秒為單位指定響應(yīng)超時(shí)。
每個(gè)路由http請(qǐng)求超時(shí)設(shè)置
- id: per_route_timeouts
uri: https://example.org
predicates:
- name: Path
args:
pattern: /delay/{timeout}
metadata:
response-timeout: 200
connect-timeout: 200
以上,來(lái)自官方docs.spring.io/spring-cloud-gateway,然而,人有禍兮旦福,照抄有問(wèn)題····
問(wèn)題/需求描述
現(xiàn)在有2個(gè)服務(wù),A-service、B-service,這2個(gè)服務(wù)的普通接口的響應(yīng)超時(shí)時(shí)間都是300ms內(nèi),但是A-service 中有文件上傳、下載的接口,文件稍大,gatway 就會(huì)報(bào)超時(shí)(504),現(xiàn)在需要把這部分接口單獨(dú)設(shè)置超時(shí)時(shí)間(別說(shuō)把文件上傳的服務(wù)拆出來(lái)單獨(dú)一個(gè)服務(wù),雖然問(wèn)題可以解決,但是暫時(shí)沒(méi)這個(gè)考慮),上代碼:
routes:
- id: files_routes
uri: http://localhost:8080
predicates:
- Path=/A-service/community/upload/**
- Host=xx.xxxx.cn
metadata:
response-timeout: 300000
connect-timeout: 300000
- id: blockchain
uri: http://localhost:8080
predicates:
- Path=/A-service/**
- Host=xx.xxxxx.cn
metadata:
response-timeout: 2000
connect-timeout: 3000
filters:
- RewritePath=/A-service, /
- id: authorization
uri: http://localhost:8081
predicates:
- Path=/B-service/**
- Host=xx.xxxx.cn
metadata:
response-timeout: 2000
connect-timeout: 3000
filters:
- RewritePath=/B-service, /
OK,訪問(wèn)一下,第一次可以,再來(lái)一下,404~! 多試幾次效果一樣,那么就懷疑這個(gè)配置的命中順序不是固定的,而是隨機(jī)的,那得解決這個(gè)問(wèn)題,找了一下官方資料,發(fā)現(xiàn)有個(gè)屬性 order 可以指定優(yōu)先級(jí)(順序),把order加上就好了。
總結(jié)
cgi 的配置文件是無(wú)序的,需要手動(dòng)通過(guò)order指定優(yōu)先級(jí)。