在開發過程中遇到的一些配置問題,記錄下來以供參考
spring-gateway版本是2.2.9-release,使用的spring cloud dependence 是 Hoxton.SR12
在依賴eureka 服務發現并自動將發現服務器加入到router中的時候,需要指定對應的服務進行添加,根據文檔描述可以使用spring.cloud.gateway.discovery.locator.include-expression
參數允許接收一個 spel表達式,用于判定當前的service instance是否允許進行自動路由,我所遇到的問題是不清楚可以依靠那些字段進行判斷,根據報錯信息,可以定位到,spel表達式執行的上下文是ServiceInstance
,具體的邏輯代碼在org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator#getRouteDefinitions
代碼如下
SpelExpressionParser parser = new SpelExpressionParser();Expression includeExpr = parser.parseExpression(this.properties.getIncludeExpression());Expression urlExpr = parser.parseExpression(this.properties.getUrlExpression());Predicate includePredicate;if (this.properties.getIncludeExpression() != null && !"true".equalsIgnoreCase(this.properties.getIncludeExpression())) {includePredicate = (instance) -> {Boolean include = (Boolean)includeExpr.getValue(this.evalCtxt, instance, Boolean.class);return include == null ? false : include;};} else {includePredicate = (instance) -> {return true;};}
urlExpr
的的默認值是 “lb://”+serverId,即spring.cloud.gateway.routes[0].uri的值 ,使用的不同服務發現具體得到的ServiceInstance會不一致,比如eureka的支持
這里提供了metadata,假設我們在配置文件中設置了對應值,那么這里就可以用
spring.cloud.gateway.discovery.locator.include-expression=metadata[xxx] == 1
這種形式進行引用,比如線上服務通過給metadata文件添加版本號表示當前服務實例非穩定版本,不讓它對外提供服務。配合上springbus,springconfig 可以非常方面的進行調整