【源码】Spring Cloud Gateway 启动时加载并缓存路由
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
public class CachingRouteDefinitionWriter implements RouteDefinitionWriter {
private final RouteDefinitionWriter delegate;
private final ApplicationEventPublisher publisher;
private final Map<String, RouteDefinition> cache = new HashMap<>();
public CachingRouteDefinitionWriter(RouteDefinitionWriter delegate, ApplicationEventPublisher publisher) {
this.delegate = delegate;
this.publisher = publisher;
}
@Override
public Mono<Void> save(Mono<RouteDefinition> route) {
return route.flatMap(r -> {
cache.put(r.getId(), r);
return delegate.save(Mono.just(r));
});
}
@Override
public Mono<Void> delete(Mono<String> routeId) {
return routeId.flatMap(id -> {
cache.remove(id);
return delegate.delete(Mono.just(id));
});
}
public Mono<RouteDefinition> get(String id) {
return Mono.justOrEmpty(cache.get(id));
}
}
这段代码实现了一个自定义的RouteDefinitionWriter
,它在保存和删除路由定义时同步更新内存中的缓存。这样,Spring Cloud Gateway在启动时可以直接从缓存中加载路由配置,而无需每次都访问外部的路由源(如配置服务器),从而提高了路由配置加载的性能并简化了部署过程。
评论已关闭