SHIHUC

好记性不如烂笔头,还可以分享给别人看看! 专注基础算法,互联网架构,人工智能领域的技术实现和应用。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

springcloud整合nacos配置中心

Posted on 2021-06-26 09:26  shihuc  阅读(2135)  评论(0编辑  收藏  举报

最近实物资产管理运维产品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配置依赖,有版本的匹配问题。