spring-cloud-kubernetes与SpringCloud Gateway (4)

上述pom文件中有以下几点需要注意:
第一、 依赖spring-cloud-kubernetes-core和spring-cloud-kubernetes-discovery,这样能用到spring-cloud-kubernetes提供的服务发现能力;
第二、依赖spring-cloud-starter-gateway,这样能用上SpringCloud的gateway能力;
第三、不要依赖spring-boot-starter-web,会和spring-cloud-starter-gateway冲突,启动时抛出以下异常:

2019-07-06 08:12:09.188 WARN 1 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'routeDefinitionRouteLocator' defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]: Unsatisfied dependency expressed through method 'routeDefinitionRouteLocator' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'modifyRequestBodyGatewayFilterFactory' defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]: Unsatisfied dependency expressed through method 'modifyRequestBodyGatewayFilterFactory' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.http.codec.ServerCodecConfigurer' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

开发SpringCloud Gateway的启动类K8sgatewaydemoApplication.java,里面也包含了网关路由配置的实例化,除了配置路径和转发服务的关系,还在请求的header中添加了extendtag属性,请注意注释的内容:

@SpringBootApplication @EnableDiscoveryClient public class K8sgatewaydemoApplication { public static void main(String[] args) { SpringApplication.run(K8sgatewaydemoApplication.class, args); } @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() //增加一个path匹配,以"/customize/hello/"开头的请求都在此路由 .route(r -> r.path("/customize/hello/**") //表示将路径中的第一级参数删除,用剩下的路径与webdemo的路径做拼接, //这里就是"lb://webdemo/hello/",能匹配到webdemo的HelloController的路径 .filters(f -> f.stripPrefix(1) //在请求的header中添加一个key&value .addRequestHeader("extendtag", "geteway-" + System.currentTimeMillis())) //指定匹配服务webdemo,lb是load balance的意思 .uri("lb://webdemo") ).build(); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpdyfp.html