NACOS配置中心获取不到配置内容

项目Spring版本

Spring Boot 2.4.5
Spring Cloud Alibaba 2021.1

由于使用的Spring boot版本较新,所以只能用2021.1这个版本的Spring Cloud Alibaba。
千万要注意各组件间的版本关系,请参考
https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E

image.png

image.png

问题

项目代码启动,服务是可以成功注册到nacos,但并未获取到nacos中的配置信息。网上很多说用bootstrap.yml的,但加了也同样无法生效。
application.yml文件内容如下:

spring:
  application:
    name: test-services
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        namespace: 123456
        file-extension: yaml
        group: TEST
      discovery:
        namespace: 123456
        group: TEST
        server-addr: 127.0.0.1:8848

想通过nacos获取spring boot项目的配置,并已在配置中心加入了以下配置:

server:
  port: 8080

spring:
  main:
    allow-bean-definition-overriding: true
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test_db?autoReconnect=true&characterEncoding=utf-8
    username: root
    password: 123456
    hikari:
      maximum-pool-size: 100
      minimum-idle: 3
      max-lifetime: 1800000
      idle-timeout: 180000
      connection-test-query: SELECT 1

分析

从Spring Boot 2.4版本开始,配置文件加载方式进行了重构。
另外也有配置的默认值变化,如下:
Spring Boot 2.3.8.RELEASE

package org.springframework.cloud.bootstrap;
public class BootstrapApplicationListener implements ApplicationListener, Ordered {
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        if ((Boolean)environment.getProperty("spring.cloud.bootstrap.enabled", Boolean.class, true)) {

Spring Boot 2.4.2

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;
    }

bootstrap.yml(bootstrap.properties)与application.yml(application.properties)执行顺序

bootstrap.yml(bootstrap.properties):用来在程序引导时执行,应用于更加早期配置信息读取,如可以使用来配置application.yml中使用到参数等
application.yml(application.properties) :应用程序特有配置信息,可以用来配置后续各个模块中需使用的公共参数等。
因此bootstrap.yml 先于 application.yml 加载

解决

添加依赖,并使用bootstrap.yml作为配置文件(因为使用application.yml是不能生效)


    org.springframework.cloud
    spring-cloud-starter-bootstrap
    3.0.3

参考

https://blog.csdn.net/weixin_43272781/article/details/116718747
https://spring-cloud-alibaba-group.github.io/github-pages/hoxton/en-us/index.html
https://spring-cloud-alibaba-group.github.io/github-pages/hoxton/zh-cn/index.html#%E5%85%B3%E4%BA%8E_nacos_config_starter%E6%9B%B4%E5%A4%9A%E7%9A%84%E9%85%8D%E7%BD%AE%E9%A1%B9%E4%BF%A1%E6%81%AF

你可能感兴趣的:(NACOS配置中心获取不到配置内容)