升级Spring Cloud Alibaba 2021.1,Spring Cloud 2020.0.1,Spring Boot 2.4.2碰到的一系列兼容性问题及

本文档提供了SpringCloud Alibaba版本升级过程中遇到的各种问题及其解决方案,包括配置文件不生效、服务间调用失败、数据库驱动兼容性问题等,旨在帮助开发者顺利完成版本迁移。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目场景:

最近介于Log4j的漏洞,Spring boot也将版本升级到了2.6.2,并更新依赖版本Upgrade to Log4j2 2.17.0 , 本打算激进些直接把Spring Cloud升级到2021.0.x,Boot升级到2.6.2,奈何Cloud Alibaba还没兼容这块,发现直接强制升级存在循环依赖的问题,目前已知Nacos没问题,Sentinel和Dubbo存在循环依赖,所以还是乖乖升级到兼容版本,并且单独升级依赖的Log4j和Logback吧。

更新过程中碰到一系列的问题,及解决方案供大家少走些弯路。

Spring Cloud Alibaba版本信息详细可查看:版本说明


问题及解决方案:

1. bootstrap.yml不生效

例如报错:Param ‘serviceName’ is illegal, serviceName is blank

因为我的Nacos配置放到了bootstrap.yml,发现读取不到Nacos配置中心的配置,后续发现控制台也不显示Nacos相关信息。

原因

从Spring Boot 2.4版本开始,配置文件加载方式进行了重构。

package org.springframework.cloud.util;
public abstract class PropertyUtils {
    public static boolean bootstrapEnabled(Environment environment) {
        return (Boolean)environment.getProperty("spring.cloud.bootstrap.enabled", Boolean.class, false) || MARKER_CLASS_EXISTS;
    }

详细可查看官方说明:config-first-bootstrap

解决方案

<!-- 引入bootstrap -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

2. 通过spring gateway访问其他服务503 service unavailable

原因

Spring Cloud 2020.0.0版本之前会自动引入Netflix Ribbon依赖,Netflix Ribbon功能跟loadbalancer一样,因Netflix公司停止维护Ribbon后, 在Spring Cloud 2020.0.0版本之后Spring使用loadbalancer替代了Ribbon, 但是loadbalancer依赖需要手动引入。

解决方案

# 引入loadbalancer
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>

后续问题

增加loadbalancer后启动提示:Spring Cloud LoadBalancer is currently working with the default cache. You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath

解决方案是引入caffeine,或者关闭cache

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>3.1.0</version>
</dependency>
访问其他服务时提示:LoadBalancerCacheManager not available, returning delegate without caching

先说有效方案,经过测试发现依赖有问题,引入依赖即可解决:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>5.2.21.RELEASE</version>
</dependency>

之前找到的网友配置,无效,以下可忽略,仅做记录

spring:
	cloud:
    loadbalancer:
      ribbon:
        enabled: false
      cache:
        enabled: true
        caffeine:
          spec: initialCapacity=500,expireAfterWrite=5s

但是发现配置有可能还会存在提示,没有生效!网络上有说Naocs discovery依赖有冲突导致没生效,exclusion spring-cloud-starter-netflix-ribbon,但是实际查看了下此版本并没有依赖这个包。

3. Loading class ‘com.mysql.jdbc.Driver’. This is deprecated. The new driver class is ‘com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

原因

项目配置:

driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
url: jdbc:log4jdbc:mysql://127.0.0.1:3306/tuine?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false

项目中使用到了log4jdbc-log4j2-jdbc4.1,升级后出现此错误提示。 因为mysql最新驱动名称为com.mysql.cj.jdbc.Driver,log4jdbc只支持com.mysql.jdbc.Driver,所以需要将自动加载数据库驱动关闭。

解决方案

resources文件下新增log4jdbc.log4j2.properties文件

log4jdbc.auto.load.popular.drivers=false
log4jdbc.drivers=com.mysql.cj.jdbc.Driver
log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator

4. Process finished with exit code 1

测试启动过程中,发现Idea直接退出,没有任何提示输出。这是Idea的设置问题

解决方案

在启动的Edit Configuration里设置指定服务的Active profiles,例如:local

5. Spring Cloud Gateway GlobalFilter自定义过滤中的同步调用和Feign调用,java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2

原因

在NonBlocking线程中再调用阻塞方法。例如Netty的线程就不允许阻塞,因为是在Netty的pipeline里,而Netty的线程本身是不允许阻塞的。

解决方案

修改为异步调用:eg.

 CompletableFuture<JSONObject> f  = CompletableFuture.supplyAsync(() -> {
     ResponseEntity<String> resEntity = restTemplate.exchange(authServiceUrl + "/permission", HttpMethod.GET, httpEntity, String.class);
     return JSONUtil.parseObj(resEntity.getBody());
 });
 JSONObject jsonObject = f.get();

6. Dubbo引入报错:org.springframework.beans.BeanInstantiationException: Failed to instantiate [feign.jaxrs2.JAXRS2Contract]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: javax/ws/rs/Path

原因

网络上有说 javax/ws/rs/Path 是属于jsr311-api.jar 包下的,引入相关jsr311-api包即可,实际测试引入netflix-ribbon即可。

解决方案

引入ribbon

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-ribbon -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
    <version>2.2.10.RELEASE</version>
</dependency>

7. When allowCredentials is true, allowedOrigins cannot contain the special value

提示allowedOrigins不允许设置*。2.4版本后需要修改此选项

When allowCredentials is true, allowedOrigins cannot contain the special value "*“since that cannot be set on the “Access-Control-Allow-Origin” response header. To allow credentials to a set of origins, list them explicitly or consider using"allowedOriginPatterns” instead.

解决方案

allowedOrigins更改为allowedOriginPatterns即可

allowedOrigins: "*"
# 替换为
allowedOriginPatterns: "*"

8. 升级后没有引入javax.validation包

原因

新版本中Spring Boot不自动包含此包,自行引入即可。

解决方案

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
    <version>2.3.3.RELEASE</version>
</dependency>

9. RestTemplate通过nacos服务名访问报错:java.net.UnknownHostException

此处还是因为2020版本不再使用netflix,没有了ribbon导致的问题,依旧是引入:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>

如出现以下报错:

An attempt was made to call a method that does not exist. The attempt was made from the following location:
    org.hibernate.validator.internal.xml.config.ValidationBootstrapParameters.<init>(ValidationBootstrapParameters.java:65)
The following method did not exist:
 javax.validation.BootstrapConfiguration.getClockProviderClassName()Ljava/lang/String;

解决方案为将 JavaEE7升级到JavaEE8

 <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0.1</version>
</dependency>
<think>好的,我现在需要处理用户关于Spring Boot 2.4.2Spring Cloud Alibaba Nacos Config 2021.1集成的请求,特别是使用spring.config.import加载Nacos配置的示例代码。首先,我得回忆一下Spring BootSpring Cloud Alibaba的版本兼容性。根据用户提供的引用[2],Spring Cloud Alibaba 2021.1对应的是Spring Cloud 2020.0.1Spring Boot 2.4.2,所以版本组合是正确的。 接下来,用户提到需要示例代码,因此我需要确保配置步骤正确。根据Spring Boot 2.4及以后的版本,配置导入方式从bootstrap.yml迁移到了使用spring.config.import,所以需要指导用户如何在application.yml中配置。需要包括Nacos服务器的地址、命名空间、data-id等信息。 另外,用户可能遇到的问题,比如依赖缺失。根据引用[3],新版本的Spring Boot不再自动包含某些包,比如spring-boot-starter-validation,但在这里可能需要的是spring-cloud-starter-alibaba-nacos-config。需要确认依赖是否正确引入,避免出现UnknownHostException,如引用[3]中的问题,可能与服务发现配置有关,但用户的问题集中在配置管理上。 然后,编写示例代码时,需要给出pom.xml中的依赖项,特别是确保Spring Cloud Alibaba的版本是2021.1,对应的Spring Boot2.4.2。同时,application.yml中的配置要正确使用spring.config.import属性,格式应该是nacos:nacos-server-ip:port?namespace=xxx&group=xxx&data-id=xxx。可能需要分步骤说明配置项,比如分解成Nacos服务器地址、命名空间、组和data-id。 还要注意是否需要启用服务发现或配置管理的相关注解,比如@EnableDiscoveryClient,但根据Spring Cloud的惯例,可能已经通过依赖自动配置,但为了保险起见,可能在启动类上添加该注解。 最后,验证步骤,比如如何读取配置,可能需要一个RestController来测试配置是否成功加载。同时,提醒用户注意配置的优先级和可能的覆盖问题,确保Nacos中的配置正确无误。 总结步骤:添加依赖、配置application.yml、添加启动类注解、编写测试接口、注意事项。需要检查每个步骤的正确性,避免遗漏关键配置项,如namespace的格式是否正确(比如不是名称而是ID),以及group是否正确(默认DEFAULT_GROUP)等。</think>### Spring Boot 2.4.2Spring Cloud Alibaba Nacos Config 2021.1集成示例 #### 1. 版本兼容性验证 根据引用[2],Spring Cloud Alibaba 2021.1版本兼容Spring Boot 2.4.x,符合要求[^2]。 #### 2. 添加依赖 ```xml <!-- pom.xml --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> <version>2021.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.4.2</version> </dependency> ``` #### 3. 配置application.yml ```yaml spring: application: name: demo-service config: import: nacos:${NACOS_SERVER:localhost:8848}?namespace=dev_namespace_id&group=DEFAULT_GROUP&data-id=demo-service.yaml cloud: nacos: username: nacos password: nacos config: server-addr: ${spring.config.import#nacos:} file-extension: yaml refresh-enabled: true ``` #### 4. 启动类配置 ```java @SpringBootApplication @EnableDiscoveryClient // 启用服务发现(可选) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` #### 5. 验证配置读取 ```java @RestController @RefreshScope public class ConfigController { @Value("${custom.config.key:default}") private String configValue; @GetMapping("/config") public String getConfig() { return "Loaded value: " + configValue; } } ``` #### 注意事项 1. **命名空间**需使用ID而非名称(在Nacos控制台查看) 2. **data-id**需包含文件扩展名,如`demo-service.yaml` 3. 若出现`UnknownHostException`,检查Nacos服务地址是否可达[^3] 4. 配置优先级:`spring.config.import` > `bootstrap.yml` > 本地配置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值