我希望使用服务发现调用在启动时设置我的 URI。例如,我想在启动时解析此路由并替换 uri 的值。理想情况下,过滤器不应该是解决方案,因为我不想每次都检查,只想在创建"路由"bean 时设置一次值。
spring:
cloud:
gateway:
routes:
- id: my-portal
uri: https://no.op # will trigger a svc disc lookup. I was hoping i could use the routes id value (my-portal) as the svc disc param
predicates:
- Path=/foo/**
filters:
- RewritePath=/foo(?<segment>.*),/${segment}
- id: my-portal-admin
uri: https://admin.com # wont trigger a Svc disc lookup
predicates:
- Path=/admin/**
filters:
- RewritePath=/foo(?<segment>.*),/${segment}
我已经审查了 https://cloud.spring.io/spring-cloud-gateway/reference/html/#the-discoveryclient-route-definition-locator,我不喜欢它,因为:
- 似乎全有或全无。有些路由我想发现 URL,有些则不想。所以我想控制该逻辑/查找
- 索引表示法非常不好,并且更愿意按照上述语法定义路由。
谢谢
一种方法是使用自动配置的PropertiesRouteDefinitionLocator
bean。获取所有RouteDefinition
并更新必要的。
下面是示例:
@SpringBootApplication
public class AuthGateway implements CommandLineRunner {
private PropertiesRouteDefinitionLocator routeDefinitionLocator;
public AuthGateway(PropertiesRouteDefinitionLocator routeDefinitionLocator) {
this.routeDefinitionLocator = routeDefinitionLocator;
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(AuthGateway.class);
app.addListeners(new ApplicationPidFileWriter());
app.run(args);
}
@Override
public void run(String... args) throws Exception {
routeDefinitionLocator.getRouteDefinitions()
.map(this::updateRouteDefinition)
.subscribe();
}
private RouteDefinition updateRouteDefinition(RouteDefinition routeDefinition) {
if(routeDefinition.getId().equals("my-portal-admin")) {
URI uri = URI.create("https://admin.com");
routeDefinition.setUri(uri);
}
return routeDefinition;
}
}