一个springcloud gateway工程demo,为了把应用注册到注册中心eureka,在gateway启动类添加注解 @EnableEurekaClient,同时pom文件中增加了配置
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
工程启动后,报错
Description:
Parameter 0 of method modifyRequestBodyGatewayFilterFactory in org.springframework.cloud.gateway.config.GatewayAutoConfiguration required a bean of type 'org.springframework.http.codec.ServerCodecConfigurer' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.http.codec.ServerCodecConfigurer' in your configuration.
问题排查过程
搜了下,大多说的是gateway 和 spring-boot-starter-web 不兼容问题,示意排除web依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</exclusion>
</exclusions>
</dependency>
修改代码排除后,启动,依然报刚开始的错误。说明,问题的症结不在web依赖这里。
继续排查发现,问题的原因是gateway和eureka的依赖有冲突。
为了将服务注册到eureka注册中心,使用了注解 @EnableEurekaClient,故而引入依赖eureka-server,见文章开篇位置。
换个方式,使用注解 @EnableDiscoveryClient 将服务注册到注册中心,去掉eureka-server依赖,启动不报错。
再回到上面,去掉排除web的依赖,恢复到最初的gateway依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
启动不报错。由此证明,这里的报错场景主要是gateway和eureka-server依赖冲突导致,与web依赖无关。
@EnableEurekaClient和@EnableDiscoveryClient
@EnableEurekaClient和@EnableDiscoveryClient 这两个注解都可以将服务注册到注册中心,他们有哪些区别呢?
使用@EnableEurekaClient的时候,引入的类路径为 import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
使用@EnableDiscoveryClient时,引入的类路径 import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableEurekaClient 是Netflix的产品,该注解仅支持将微服务注册到eureka注册中心,不支持其它注册中心。
@EnableDiscoveryClient 是springcloud团队的产品,该注解不仅支持将微服务注册到eureka,还支持将微服务注册到其它注册中心,如 nacos,consul等。
从使用范围来讲,@EnableDiscoveryClient使用更广一些,加之eureka2.0已不再维护,eureka注册中心后续的使用将会减少,随之@EnableEureakaClient使用会降低。基于此,后续服务注册发现这里@EnableDiscoveryClient使用会更广。