1. 程式人生 > 其它 >springcloud整合nacos配置中心

springcloud整合nacos配置中心

最近實物資產管理運維產品pams系統架構搭建中,涉及到配置中心的問題,在這裡做個記錄,作為第一手經驗分享,也是自我備忘吧。

整個體系,目前一共有10+箇中等粒度的微服務,每個服務都有自己的yml配置檔案,這些給人的感覺就有些不太方便,尤其是上系統後,若僅僅因為改一個引數,重新打包(jar檔案解壓後,再打包回來,編碼校驗過不了。。。),或者就算是war包,也得上系統重新改檔案,然後重啟啊,不能集中管控,效率低下,不利於維護。

於是,打算引入配置中心,配置中心是一個非常陳舊的概念,實現方式也有非常多的種類,但是實現思想基本是一樣的,那就是中心管控配置,修改後,服務端立刻監聽到,並且按需生效,不需要重新啟動服務程式。 當前比較主流的,可能就算Apollo,Nacos,Consul等等,還可以自己設計實現。。。

好了,接下來說下本次的經歷吧。

1. 框架版本資訊

springcloud 版本greenwich.RELEASE
springboot 版本2.1.9.RELEASE
Nacos server 版本2.0.1

2. Nacos server配置
2.1 從官方網站下載原始碼(https://github.com/alibaba/nacos/tree/2.0.1)並做編譯和基本配置

G:\workspace\nacos-2.0.1\nacos-2.0.1\mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U

編譯完成後,將G:\workspce\nacos-2.0.1\nacos-2.0.1\distribution\target\nacos-server-2.0.1目錄下的nacos拷貝到G:\workspce\nacos-2.0.1\nacos-2.0.1\distribution\下面。
進入G:\workspce\nacos-2.0.1\nacos-2.0.1\distribution\nacos\conf, 修改application.properties檔案,主要修改下面的引數(資料來源相關資訊):

#*************** Spring Boot Related Configurations ***************#
### Default web context path:
server.servlet.contextPath=/nacos
### Default web server port:
server.port=8848
#*************** Network Related Configurations ***************#
### If prefer hostname over ip for Nacos server addresses in
cluster.conf: # nacos.inetutils.prefer-hostname-over-ip=false ### Specify local server's IP: nacos.inetutils.ip-address=10.94.100.131 #*************** Config Module Related Configurations ***************# ### If use MySQL as datasource: spring.datasource.platform=mysql ### Count of DB: db.num=1 ### Connect URL of DB: db.url.0=jdbc:mysql://100.95.198.30:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC db.user.0=xxx db.password.0=xxxxx

2.2 初始化資料來源

建立一個數據庫命名為nacos,並將G:\workspce\nacos-2.0.1\nacos-2.0.1\distribution\nacos\conf下的nacos-mysql.sql匯入到這個nacos資料庫,匯入完成後,有下面的表。
config_info, config_info_aggr, config_info_beta, config_info_tag, config_tags_relation, group_capacity, his_config_info, permissions, roles, tenant_capacity, tenant_info, users

2.3 啟動nacos server

因為這裡驗證的邏輯,是在windows環境下,所以才有bat的腳步啟動,startup.bat -m standalone

G:\workspce\nacos-2.0.1\nacos-2.0.1\distribution\nacos\bin>startup.cmd -m standalone
"nacos is starting with standalone"

         ,--.
       ,--.'|
   ,--,:  : |                                           Nacos 2.0.1
,`--.'`|  ' :                       ,---.               Running in stand alone mode, All function modules
|   :  :  | |                      '   ,'\   .--.--.    Port: 8848
:   |   \ | :  ,--.--.     ,---.  /   /   | /  /    '   Pid: 10968
|   : '  '; | /       \   /     \.   ; ,. :|  :  /`./   Console: http://10.94.100.131:8848/nacos/index.html
'   ' ;.    ;.--.  .-. | /    / ''   | |: :|  :  ;_
|   | | \   | \__\/: . ..    ' / '   | .; : \  \    `.      https://nacos.io
'   : |  ; .' ," .--.; |'   ; :__|   :    |  `----.   \
|   | '`--'  /  /  ,.  |'   | '.'|\   \  /  /  /`--'  /
'   : |     ;  :   .'   \   :    : `----'  '--'.     /
;   |.'     |  ,     .-./\   \  /            `--'---'
'---'        `--`---'     `----'

2.4 登入nacos服務

預設的賬號密碼是nacos/nacos

登入進來後的介面如下:

在nacos側,配置上dataId,以及具體的引數

3. springcloud服務側配置

3.1 在resources目錄下構建bootstrap.yml(bootstrap載入順序優先於application)

spring:
  application:
    name: micro-system-mgmt
  #切換配置檔案
  profiles:
    active: dev
  cloud:
    nacos:
      config:
        server-addr: 10.94.100.131:8848
        file-extension: yaml

3.2 pom.xml

在pom.xml中新增下面的依賴

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

3.3 原來預設配置資訊的配置

類似資料庫,redis快取資訊,可以依舊儲存在application-dev.yml/application-prd.yml中, 不區分生產和測試等環境的引數,例如日誌,mybatis,pagehelper等,可以寫入application.xml。
可變的引數,涉及到業務相關的邏輯引數,可以通過Nacos配置服務進行接管。

說明:

1. 資料庫連線等所有的資訊,其實都可以通過Nacos進行接管。 2. 本地配置application-dev.yml或者application-prd.yml,同時配置Nacos配置中心,依然可以同時作用。相同的引數,配置中心的資料優先順序高於本地配置檔案,替換本地配置.

4. springcloud應用層程式碼要求

在需要動態變更引數的地方,需要通過@RefreshScope配合@Value的方式,或者@ConfigurationProperties方式,觸發動態重新整理。

@Api("測試各種框架的基本功能是否OK")
@RestController
@RequestMapping("/ts")
@RefreshScope //出於靈活應用考慮,建議採用此註解
public class TestController {

    @Value("${nacos.hello}")
    private String hello;
    
    private Logger logger = LoggerFactory.getLogger(TestController.class);

    @ApiOperation(value = "介面呼叫,驗證Nacos配置", notes = "整合Nacos的配置管理,引數是否實時重新整理")
    @ApiImplicitParam(name = "param", value = "引數名稱", required = true, dataType = "String", paramType = "query")
    @GetMapping(value = "/nacos/info")
    public String checkNacos(@RequestParam("param") String param) {
        logger.info("hello: " + hello);
        return hello;
    }
}

啟動執行報錯:

2021-06-22 10:27:48.739 INFO [main]o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization:330 - Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$e02d6bc] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.9.RELEASE)

2021-06-22 10:27:50.024 INFO [main]com.taikang.pams.systemmgmt.SystemMgmtApplication.logStartupProfileInfo:652 - The following profiles are active: dev
2021-06-22 10:27:51.791 WARN [main]org.springframework.boot.actuate.endpoint.EndpointId.logWarning:131 - Endpoint ID 'service-registry' contains invalid characters, please migrate to a valid format.
2021-06-22 10:27:51.880 WARN [main]org.springframework.boot.actuate.endpoint.EndpointId.logWarning:131 - Endpoint ID 'hystrix.stream' contains invalid characters, please migrate to a valid format.
2021-06-22 10:27:52.312 INFO [main]org.springframework.cloud.context.scope.GenericScope.setSerializationId:294 - BeanFactory id=016fb783-119b-3df3-91bb-89efaaa5451d
2021-06-22 10:27:52.398 INFO [main]o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization:330 - Bean 'druid-stat-pointcut' of type [org.springframework.aop.support.JdkRegexpMethodPointcut] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-06-22 10:27:52.400 INFO [main]o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization:330 - Bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0' of type [org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-06-22 10:27:52.768 INFO [main]o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization:330 - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$f1e8d3bf] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-06-22 10:27:52.814 INFO [main]o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization:330 - Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$e02d6bc] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-06-22 10:27:53.416 INFO [main]o.s.boot.web.embedded.tomcat.TomcatWebServer.initialize:90 - Tomcat initialized with port(s): 9002 (http)
2021-06-22 10:27:53.438 INFO [main]org.apache.coyote.http11.Http11NioProtocol.log:173 - Initializing ProtocolHandler ["http-nio-9002"]
2021-06-22 10:27:53.449 INFO [main]org.apache.catalina.core.StandardService.log:173 - Starting service [Tomcat]
2021-06-22 10:27:53.449 INFO [main]org.apache.catalina.core.StandardEngine.log:173 - Starting Servlet engine: [Apache Tomcat/9.0.26]
2021-06-22 10:27:53.673 INFO [main]o.a.catalina.core.ContainerBase.[Tomcat].[localhost].[/].log:173 - Initializing Spring embedded WebApplicationContext
2021-06-22 10:27:53.674 INFO [main]org.springframework.web.context.ContextLoader.prepareWebApplicationContext:284 - Root WebApplicationContext: initialization completed in 3628 ms
2021-06-22 10:27:53.917 WARN [main]com.netflix.config.sources.URLConfigurationSource.<init>:121 - No URLs will be polled as dynamic configuration sources.
2021-06-22 10:27:53.918 INFO [main]com.netflix.config.sources.URLConfigurationSource.<init>:122 - To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2021-06-22 10:27:53.935 INFO [main]com.netflix.config.DynamicPropertyFactory.getInstance:281 - DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration@61da0413
2021-06-22 10:27:55.080 INFO [main]com.alibaba.druid.pool.DruidDataSource.init:930 - {dataSource-1} inited
2021-06-22 10:27:56.445 INFO [main]org.springframework.cloud.commons.util.InetUtils.convertAddress:170 - Cannot determine local hostname
2021-06-22 10:27:56.915 INFO [main]o.s.boot.actuate.endpoint.web.ServletEndpointRegistrar.register:74 - Registered '/actuator/hystrix.stream' to hystrix.stream-actuator-endpoint
2021-06-22 10:27:57.988 INFO [main]o.s.boot.actuate.endpoint.web.EndpointLinksResolver.<init>:58 - Exposing 20 endpoint(s) beneath base path '/actuator'
2021-06-22 10:27:58.186 INFO [main]s.d.s.web.PropertySourcedRequestMappingHandlerMapping.initHandlerMethods:69 - Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
2021-06-22 10:27:58.221 WARN [main]com.netflix.config.sources.URLConfigurationSource.<init>:121 - No URLs will be polled as dynamic configuration sources.
2021-06-22 10:27:58.221 INFO [main]com.netflix.config.sources.URLConfigurationSource.<init>:122 - To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2021-06-22 10:27:58.502 INFO [main]o.s.scheduling.concurrent.ThreadPoolTaskExecutor.initialize:171 - Initializing ExecutorService 'applicationTaskExecutor'
2021-06-22 10:28:00.592 INFO [main]org.springframework.cloud.commons.util.InetUtils.convertAddress:170 - Cannot determine local hostname
2021-06-22 10:28:01.072 INFO [main]o.s.cloud.netflix.eureka.InstanceInfoFactory.create:71 - Setting initial instance status as: STARTING
2021-06-22 10:28:01.111 INFO [main]com.netflix.discovery.DiscoveryClient.<init>:349 - Initializing Eureka in region us-east-1
2021-06-22 10:28:01.474 INFO [main]com.netflix.discovery.provider.DiscoveryJerseyProvider.<init>:70 - Using JSON encoding codec LegacyJacksonJson
2021-06-22 10:28:01.475 INFO [main]com.netflix.discovery.provider.DiscoveryJerseyProvider.<init>:71 - Using JSON decoding codec LegacyJacksonJson
2021-06-22 10:28:01.643 INFO [main]com.netflix.discovery.provider.DiscoveryJerseyProvider.<init>:80 - Using XML encoding codec XStreamXml
2021-06-22 10:28:01.644 INFO [main]com.netflix.discovery.provider.DiscoveryJerseyProvider.<init>:81 - Using XML decoding codec XStreamXml
2021-06-22 10:28:02.061 INFO [main]c.n.discovery.shared.resolver.aws.ConfigClusterResolver.getClusterEndpoints:43 - Resolving eureka endpoints via configuration
2021-06-22 10:28:02.161 INFO [main]com.netflix.discovery.DiscoveryClient.fetchRegistry:958 - Disable delta property : false
2021-06-22 10:28:02.161 INFO [main]com.netflix.discovery.DiscoveryClient.fetchRegistry:959 - Single vip registry refresh property : null
2021-06-22 10:28:02.161 INFO [main]com.netflix.discovery.DiscoveryClient.fetchRegistry:960 - Force full registry fetch : false
2021-06-22 10:28:02.161 INFO [main]com.netflix.discovery.DiscoveryClient.fetchRegistry:961 - Application is null : false
2021-06-22 10:28:02.161 INFO [main]com.netflix.discovery.DiscoveryClient.fetchRegistry:962 - Registered Applications size is zero : true
2021-06-22 10:28:02.162 INFO [main]com.netflix.discovery.DiscoveryClient.fetchRegistry:964 - Application version is -1: true
2021-06-22 10:28:02.162 INFO [main]com.netflix.discovery.DiscoveryClient.getAndStoreFullRegistry:1047 - Getting all instance registry info from the eureka server
2021-06-22 10:28:02.524 INFO [main]com.netflix.discovery.DiscoveryClient.getAndStoreFullRegistry:1056 - The response status is 200
2021-06-22 10:28:02.526 INFO [main]com.netflix.discovery.DiscoveryClient.initScheduledTasks:1270 - Starting heartbeat executor: renew interval is: 30
2021-06-22 10:28:02.529 INFO [main]com.netflix.discovery.InstanceInfoReplicator.<init>:60 - InstanceInfoReplicator onDemand update allowed rate per min is 4
2021-06-22 10:28:02.533 INFO [main]com.netflix.discovery.DiscoveryClient.<init>:449 - Discovery Client initialized at timestamp 1624328882531 with initial instances count: 0
2021-06-22 10:28:02.541 INFO [main]o.s.c.n.eureka.serviceregistry.EurekaServiceRegistry.register:42 - Registering application MICRO-SYSTEM-MGMT with eureka with status UP
2021-06-22 10:28:02.542 INFO [main]com.netflix.discovery.DiscoveryClient.notify:1305 - Saw local status change event StatusChangeEvent [timestamp=1624328882542, current=UP, previous=STARTING]
2021-06-22 10:28:02.544 INFO [main]s.d.spring.web.plugins.DocumentationPluginsBootstrapper.start:160 - Context refreshed
2021-06-22 10:28:02.553 INFO [DiscoveryClient-InstanceInfoReplicator-0]com.netflix.discovery.DiscoveryClient.register:826 - DiscoveryClient_MICRO-SYSTEM-MGMT/localhost:micro-system-mgmt:9002: registering service...
2021-06-22 10:28:02.644 INFO [main]s.d.spring.web.plugins.DocumentationPluginsBootstrapper.start:163 - Found 1 custom documentation plugin(s)
2021-06-22 10:28:02.753 INFO [main]s.d.spring.web.scanners.ApiListingReferenceScanner.scan:41 - Scanning for api listing references
2021-06-22 10:28:02.837 INFO [DiscoveryClient-InstanceInfoReplicator-0]com.netflix.discovery.DiscoveryClient.register:835 - DiscoveryClient_MICRO-SYSTEM-MGMT/localhost:micro-system-mgmt:9002 - registration status: 204
2021-06-22 10:28:02.938 INFO [main]s.d.s.w.readers.operation.CachingOperationNameGenerator.startingWith:40 - Generating unique operation named: userUsingGET_1
2021-06-22 10:28:02.969 WARN [main]o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext.refresh:557 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.testController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'nacos.hello' in value "${nacos.hello}"
2021-06-22 10:28:02.973 INFO [main]o.s.scheduling.concurrent.ThreadPoolTaskExecutor.shutdown:208 - Shutting down ExecutorService 'applicationTaskExecutor'
2021-06-22 10:28:03.002 INFO [main]com.alibaba.druid.pool.DruidDataSource.close:1825 - {dataSource-1} closed
2021-06-22 10:28:03.261 WARN [AsyncReporter{org.springframework.cloud.sleuth.zipkin2.sender.RestTemplateSender@38cfecf3}]o.s.c.annotation.AnnotationConfigApplicationContext.refresh:557 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'eurekaRibbonClientConfiguration': Unsatisfied dependency expressed through field 'eurekaConfig'; nested exception is org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'eurekaInstanceConfigBean': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
2021-06-22 10:28:03.264 INFO [main]com.netflix.discovery.DiscoveryClient.shutdown:888 - Shutting down DiscoveryClient ...
2021-06-22 10:28:06.266 INFO [main]com.netflix.discovery.DiscoveryClient.unregister:922 - Unregistering ...
2021-06-22 10:28:06.282 INFO [main]com.netflix.discovery.DiscoveryClient.unregister:924 - DiscoveryClient_MICRO-SYSTEM-MGMT/localhost:micro-system-mgmt:9002 - deregister  status: 200
2021-06-22 10:28:06.293 INFO [main]com.netflix.discovery.DiscoveryClient.shutdown:911 - Completed shut down of DiscoveryClient
2021-06-22 10:28:06.294 INFO [main]org.apache.catalina.core.StandardService.log:173 - Stopping service [Tomcat]
2021-06-22 10:28:06.298 WARN [main]org.apache.catalina.loader.WebappClassLoaderBase.log:173 - The web application [ROOT] appears to have started a thread named [RxIoScheduler-1 (Evictor)] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.misc.Unsafe.park(Native Method)
 java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
 java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
 java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
 java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
 java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2021-06-22 10:28:06.315 INFO [main]o.s.b.a.logging.ConditionEvaluationReportLoggingListener.logMessage:136 - 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-06-22 10:28:06.338 ERROR[main]org.springframework.boot.SpringApplication.reportFailure:823 - Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.testController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'nacos.hello' in value "${nacos.hello}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:382)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$1(AbstractBeanFactory.java:356)
    at org.springframework.cloud.context.scope.GenericScope$BeanLifecycleWrapper.getBean(GenericScope.java:390)
    at org.springframework.cloud.context.scope.GenericScope.get(GenericScope.java:184)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:353)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105)
    at org.springframework.cloud.context.scope.refresh.RefreshScope.eagerlyInitialize(RefreshScope.java:130)
    at org.springframework.cloud.context.scope.refresh.RefreshScope.start(RefreshScope.java:121)
    at org.springframework.cloud.context.scope.refresh.RefreshScope.onApplicationEvent(RefreshScope.java:115)
    at org.springframework.cloud.context.scope.refresh.RefreshScope.onApplicationEvent(RefreshScope.java:71)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:402)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:359)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:896)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:162)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:552)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204)
    at com.taikang.pams.systemmgmt.SystemMgmtApplication.main(SystemMgmtApplication.java:57)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'nacos.hello' in value "${nacos.hello}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:237)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:211)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:851)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1175)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:595)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:376)
    ... 28 common frames omitted

查閱網路經驗以及官方文件,都有各種說辭,Nacos的版本和springcloud之間有較為密切的關係,可以說Nacos的版本相容性不是太好麼?嘗試了幾次,最終將springcloud服務側的pom配置調整為下面的內容:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>2.1.0.RELEASE</version>
</dependency>

然後再次啟動,就正常了,通過正常啟動的日誌可以看出,啟動過程中,有nacos相關的日誌列印:

2021-06-22 10:40:20.532 INFO [main]c.alibaba.cloud.nacos.client.NacosPropertySourceBuilder.loadNacosData:87 - Loading nacos data, dataId: 'micro-system-mgmt-dev.yaml', group: 'DEFAULT_GROUP'
2021-06-22 10:40:20.552 INFO [main]o.s.c.b.config.PropertySourceBootstrapConfiguration.initialize:98 - Located property source: CompositePropertySource {name='NACOS', propertySources=[NacosPropertySource {name='micro-system-mgmt-dev.yaml'}, NacosPropertySource {name='micro-system-mgmt.yaml'}]}
2021-06-22 10:40:20.584 INFO [main]com.taikang.pams.systemmgmt.SystemMgmtApplication.logStartupProfileInfo:652 - The following profiles are active: dev

下面看看重新整理操作:

修改配置後,點擊發布:

測試:

整體來看,Nacos使用還是比較簡單的,唯獨要注意的是Nacos與專案整合的時候,pom配置依賴,有版本的匹配問題。