likes
comments
collection
share

记一次SpringCloudAlibaba升级踩坑记录

作者站长头像
站长
· 阅读数 17

前言

本文主要介绍在升级SpringCloudAlibaba版本的时候遇到的两个坑:一是bootstrap配置文件不生效问题,二是如何不使用bootstrap配置文件来与Nacos整合。

正文

公司项目技术框架用的是SpringCloudAlibaba系列,最近要启动一个新项目,想着既然是新项目就用一些新版本的组件,于是开始了版本升级折腾之旅。

版本问题

公司目前其他项目使用的版本如下:

  • SpringBoot:2.3.12.RELEASE

  • SpringCloud:2.2.9.RELEASE

  • SpringCloudAlibaba:2.2.7.RELEASE

由于之前有客户要求指定项目使用SpringBoot的版本为2.5.6,所以先把SpringBoot的版本定下了暂定为2.5.6。于是打开项目脚手架打算生成一个项目框架,结果打开网页傻眼了,为啥SpringBoot版本没有2.5.x呢??

记一次SpringCloudAlibaba升级踩坑记录

然后,打开SpringCloudAlibabaGitHub的版本说明,嗯?也是没有SpringBoot2.5.x的版本。

记一次SpringCloudAlibaba升级踩坑记录

后来,查看Spring的官网,发现SpringBoot2.5.x和SpringBoot2.4.x对应SpringCloud的版本都是2020.0.x。通过这个网址也可以查到start.spring.io/actuator/in…

最后,因为这个项目比较小,也不太重要,就用了SpringCloudAlibaba GitHub上2021.x分支的最新版本,最终引入版本如下:

记一次SpringCloudAlibaba升级踩坑记录

bootstrap配置文件

基本的Jar版本弄好了,把原来项目的bootstrap.yaml文件复制一份改一改,启动项目试试吧,配置文件内容如下:

spring:
  application:
    name: example
  cloud:
    nacos:
      username: nacos
      password: nacos
      server-addr: 127.0.0.1:8848
      config:
        namespace: test
        file-extension: yaml
        extension-configs:
          - data-id: common-redis.yaml
      discovery:
        namespace: test

不出意外的话,就要出意外了,项目无法启动,还给出了提示没有spring.config.import属性:

记一次SpringCloudAlibaba升级踩坑记录

嗯?什么鬼?于是面向ChatGPT编程,得知在SpringBoot 2.4.x的版本之后,对于bootstrap.properties/bootstrap.yaml配置文件的支持,需要导入spring-cloud-starter-bootstrap依赖。

记一次SpringCloudAlibaba升级踩坑记录

废话不多说,加上以下依赖启动项目,嗯?居然可以了。这么神奇吗?什么原理?难道这个依赖包里做了什么解析配置的东西?

implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap:3.1.5'

找到这个依赖包,打开看看里面有神奇的处理,打开之后发现只有一个Marker类而且还是一个抽象的,难道是这个依赖包又依赖了其他的依赖?打开pom,发现也只是依赖了spring-cloud-starter

随后,看到了Marker类上面有一段注释,意思是这是一个标记类,如果存在的话就会启用bootstrap,效果和spring.cloud.bootstrap.enabled=true一样。也就是如果有spring.cloud.bootstrap.enabled=true这个配置的话,也可以不用加上这个依赖。

记一次SpringCloudAlibaba升级踩坑记录

来,再来试一次,加上启动参数-Dspring.cloud.bootstrap.enabled=true,然后去掉spring-cloud-starter-bootstrap依赖,启动项目,效果是一样的。

到底什么原理呢?debug走一下流程,发现在这里有个判断BootstrapApplicationListener#onApplicationEvent,是否启用bootstrap,启用的条件是spring.cloud.bootstrap.enabled属性为true,或者存在org.springframework.cloud.bootstrap.marker.Marker这个标记类,啊!终于明白了。

记一次SpringCloudAlibaba升级踩坑记录

记一次SpringCloudAlibaba升级踩坑记录

application配置文件

原本到这里就可以结束了,又想到,如果不使用bootstrap配置文件的话,该如何改呢?换成application.yaml试试。

发现还是报No spring.config.import property has been defined这个错误,那就加上这个属性试试。那么值是什么呢?查了下SpringCloudAlibaba的官方示例,需要把nacos中的配置通过import导入进来,修改如下:

spring:
  application:
    name: example
  cloud:
    nacos:
      username: nacos
      password: nacos
      server-addr: 127.0.0.1:8848
      config:
        namespace: test
        file-extension: yaml
      discovery:
        namespace: test
  config:
    import:
      - nacos:example   
      - nacos:common-redis.yaml

再次运行项目就可以了。

总结

本次升级SpringCloudAlibaba版本遇到的几个问题,记录一下,虽然折腾但还是有些收货的,最后,还是没有弄清楚问什么SpringCloudbootstrap配置文件从默认启用改成不启用了呢,有没有小伙伴知道的给说下?