Spring Cloud Gateway使用K8S (Kubernetes)的云原生服务发现
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.filter.factory.rewrite.Config;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ConfigurationService;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.cloud.gateway.support.ConfigurationProperties;
import org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator;
import org.springframework.cloud.gateway.discovery.DiscoveryLocatorProperties;
import org.springframework.cloud.kubernetes.discovery.KubernetesDiscoveryClient;
import org.springframework.cloud.kubernetes.discovery.KubernetesServiceInstance;
import org.springframework.cloud.kubernetes.discovery.KubernetesDiscoveryProperties;
@Configuration
public class KubernetesGatewayConfiguration {
private final KubernetesDiscoveryClient kubernetesDiscoveryClient;
private final KubernetesDiscoveryProperties kubernetesDiscoveryProperties;
public KubernetesGatewayConfiguration(KubernetesDiscoveryClient kubernetesDiscoveryClient, KubernetesDiscoveryProperties kubernetesDiscoveryProperties) {
this.kubernetesDiscoveryClient = kubernetesDiscoveryClient;
this.kubernetesDiscoveryProperties = kubernetesDiscoveryProperties;
}
@Bean
public DiscoveryClientRouteDefinitionLocator discoveryClientRouteDefinitionLocator(
ConfigurationService configurationService) {
return new DiscoveryClientRouteDefinitionLocator(
discovery,
discoveryProperties,
configurationService);
}
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("path_route", r -> r.path("/get")
.filters(f -> f.addResponseHeader("Hello", "World"))
.uri("http://localhost:8080"))
.build();
}
}
这个代码示例展示了如何在Spring Cloud Gateway中使用Kubernetes作为服务发现的方式来定义路由。它创建了一个名为DiscoveryClientRouteDefinitionLocator
的Bean,该Bean使用KubernetesDiscoveryClient
和KubernetesDiscoveryProperties
来自动从Kubernetes服务列表中生成路由信息。同时,它还定义了一个简单的路由,将路径为/get
的请求转发到本地的8080
端口,并通过过滤器添加了一个响应头。
评论已关闭