Sping Cloud + Eureka(作为注册中心) + Nacos(作为配置中心)
- Spring Cloud是一个分布式的微服务框架,它基于Spring Boot框架,通过将不同的微服务框架集成至一个容器中,简化开发者的代码量。
- Eureka是Spring Cloud中的服务注册与发现中心,允许进行服务注册和查找其他服务。通过Spring Cloud和Eureka的结合,可以让开发人员更加方便的构建和管理微服务。
- Nacos是一个开源的分布式配置中心和服务发现平台,由阿里巴巴集团提供支持。它可以帮助开发者实现微服务架构中的服务注册、发现、配置和管理等功能。Nacos支持多种数据源,包括本地文件、HTTP、MySQL等,同时还支持多种语言和框架,比如Java、Spring Cloud、Dubbo、Kubernetes等。Nacos还提供了多种管理工具和API,方便开发者进行配置和管理。
我们在搭建自己的微服务的时候,可以选择使用eureka作为我们微服务的注册中心,使用nacos作为微服务的配置中心,接下来我们可以看下具体的搭建过程:
(以下过程只展示Spring Cloud + Nacos的搭建过程,至于集成eureka的可以另行查找具体对接流程)
一、项目搭建
在父pom文件中引入 spring-cloud-alibaba-dependencies
依赖后,子pom中引入spring-cloud-starter-alibaba-nacos-config
依赖:
<!-- nacos的配置管理依赖 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
注意:如果想使用bootstrap文件进行配置,spring Boot2.4以后的版本需要添加spring-cloud-starter-bootstrap
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
Spring Cloud的注解 @EnableDiscoveryClient 是选择是否开启服务注册发现功能,因为我们使用eureka作为注册中心,所以这里就不需要在使用在使用nacos作为注册中心。作为配置中心的时候可以选择不加这个注解。
二、修改配置文件
使用Spring Cloud集成nacos的时候,nacos配置中心的配置项只能放到bootstrap.yml(.properties)中。在resource下的bootstrap.yml中添加一下配置信息。
spring:
application:
name: async-service
cloud:
nacos:
#配置中心
config:
server-addr: 127.0.0.1:8848
file-extension: yml
refresh-enabled: true #是否动态刷新
namespace: a42d161c6088e867606aefbbffbffde9 #命名空间对应的id,如果是在public空间,可以不配置此项
profiles:
active: dev
在nacos中,其配置管理中的dataId的命名规则如下:
${prefix}-${spring.profiles.active}.${file-extension}
prefix默认为spring.application.name的值
当通过配置文件来指定spring.profiles.active时,spring.profiles.active必须放在bootstrap.yml(.properties)文件中。当spring.profiles.active 为空时,dataId格式中对应的连接符 - 也将不存在,dataId 的拼接格式就变成
${prefix}.${file-extension}
file-exetension为配置内容的数据格式,默认为properties,可以通过配置项 spring.cloud.nacos.config.file-extension来配置,此处配置的格式类型需要和nacos后台中创建的配置类型一致。
到此,代码层面的配置结束了,接下来我们来看下nacos平台的操作。
三、nacos的启动与下载
下载地址:https://github.com/alibaba/nacos/releases
此处我们以最新的版本进行下载,此次为下载至本机电脑(windows)
下载完成后解压至文件夹后找到安装目录下的D:\Nacos\bin\startup.cmd,右键编辑将set MODE="cluster"
改为set MODE="standalone"
,此处修改的目的是在本地启动单机模式的情况下,要将集群修改为单机模式,不然启动会报错。
修改后,双击启动startup.cmdConsole后面的地址就是nacos配置中心的默认地址,复制网址进入,账号密码:nacos/nacos
进入页面,页面如下。
我们可以选择创建一个新的配置
其中Data ID 为自定义扩展,其命名规则为:[服务名称]-[环境].[后缀名]
Group:分组名称,第一次可以选择默认的分组
匹配格式:使用yml格式
配置内容:填写基本配置信息
spring.application.name对应的就是服务名称
profiles.active对应的具体环境
file-extension对应的后缀名已经配置文件格式
添加完成后发布配置信息
四、创建controller进行测试
@RefshScope可以是nacos客户端运行过程中可以获取到配置中心的配置变化然后进行更新而不用重新启动服务
测试代码如下:
package com.nameli.async.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author NAME-L
* @Description TODO
* @className TestController
* @date 2023-09-16 15:29:52
*/
@RequestMapping("/test")
@RestController
@RefreshScope
public class TestController {
@Value("${config.value}")
private String configValue;
@Autowired
private ConfigurableApplicationContext context;
@PostMapping("/context")
public String test() {
return context.getEnvironment().getProperty("config.appName");
}
@PostMapping("/value")
public String testB() {
return configValue;
}
}
服务配置文件内容
# application.yml
server:
port: 8090
spring:
application:
name: manage-async
profiles:
active: dev
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
file-extension: yml
refresh-enabled: true
eureka:
instance:
hostname: async-service
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:8888/eureka/
# bootstrap.yml
spring:
application:
name: async-service
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
file-extension: yml
refresh-enabled: true #是否动态刷新
profiles:
active: dev
注意:此时的application.yml中的spring.application.name是manage-async,而bootstrap.yml文件里的spring.application.name是async-service(此处有问题)
启动项目失败,项目报错,返回提示:Could not resolve placeholder 'config.value' in value "${config.value}"
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.7.RELEASE)
2023-09-16 21:55:50.139 INFO 21032 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
2023-09-16 21:55:50.221 WARN 21032 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: None of labels [] found
2023-09-16 21:55:50.222 INFO 21032 --- [ main] c.a.n.c.c.impl.LocalConfigInfoProcessor : LOCAL_SNAPSHOT_PATH:C:\Users\57861\nacos\config
2023-09-16 21:55:50.245 INFO 21032 --- [ main] c.a.nacos.client.config.impl.Limiter : limitTime:5.0
2023-09-16 21:55:50.259 WARN 21032 --- [ main] c.a.c.n.c.NacosPropertySourceBuilder : Ignore the empty nacos configuration and get it based on dataId[manage-async] & group[DEFAULT_GROUP]
2023-09-16 21:55:50.262 WARN 21032 --- [ main] c.a.c.n.c.NacosPropertySourceBuilder : Ignore the empty nacos configuration and get it based on dataId[manage-async.yml] & group[DEFAULT_GROUP]
2023-09-16 21:55:50.265 INFO 21032 --- [ main] c.a.nacos.client.config.utils.JvmUtil : isMultiInstance:false
2023-09-16 21:55:50.268 INFO 21032 --- [ main] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-manage-async-dev.yml,DEFAULT_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-manage-async.yml,DEFAULT_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-manage-async,DEFAULT_GROUP'}]
2023-09-16 21:55:50.270 INFO 21032 --- [ main] com.nameli.async.ManageAsyncApplication : The following profiles are active: dev
2023-09-16 21:55:50.661 INFO 21032 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=921fe981-b68a-3be8-a792-0eabb4b82761
2023-09-16 21:55:50.664 INFO 21032 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
2023-09-16 21:55:50.667 INFO 21032 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named 'taskScheduler' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.
2023-09-16 21:55:50.669 INFO 21032 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.
2023-09-16 21:55:50.712 INFO 21032 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.integration.config.IntegrationManagementConfiguration' of type [org.springframework.integration.config.IntegrationManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-09-16 21:55:50.716 INFO 21032 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration$IntegrationJmxConfiguration' of type [org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration$IntegrationJmxConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-09-16 21:55:50.720 INFO 21032 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration' of type [org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-09-16 21:55:50.723 INFO 21032 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'mbeanServer' of type [com.sun.jmx.mbeanserver.JmxMBeanServer] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-09-16 21:55:50.729 INFO 21032 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'integrationChannelResolver' of type [org.springframework.integration.support.channel.BeanFactoryChannelResolver] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-09-16 21:55:50.730 INFO 21032 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'integrationDisposableAutoCreatedBeans' of type [org.springframework.integration.config.annotation.Disposables] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-09-16 21:55:50.921 INFO 21032 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8090 (http)
2023-09-16 21:55:50.928 INFO 21032 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-09-16 21:55:50.928 INFO 21032 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2023-09-16 21:55:50.930 INFO 21032 --- [ main] o.a.catalina.core.AprLifecycleListener : Loaded Apache Tomcat Native library [1.2.23] using APR version [1.7.0].
2023-09-16 21:55:50.930 INFO 21032 --- [ main] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2023-09-16 21:55:50.930 INFO 21032 --- [ main] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2023-09-16 21:55:50.933 INFO 21032 --- [ main] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.1.1c 28 May 2019]
2023-09-16 21:55:51.011 INFO 21032 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2023-09-16 21:55:51.011 INFO 21032 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 732 ms
2023-09-16 21:55:51.062 WARN 21032 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2023-09-16 21:55:51.062 INFO 21032 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2023-09-16 21:55:51.065 WARN 21032 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2023-09-16 21:55:51.065 INFO 21032 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2023-09-16 21:55:51.162 INFO 21032 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2023-09-16 21:55:52.007 INFO 21032 --- [ main] DiscoveryClientOptionalArgsConfiguration : Eureka HTTP Client uses Jersey
2023-09-16 21:55:52.345 WARN 21032 --- [ main] ockingLoadBalancerClientRibbonWarnLogger : You already have RibbonLoadBalancerClient on your classpath. It will be used by default. As Spring Cloud Ribbon is in maintenance mode. We recommend switching to BlockingLoadBalancerClient instead. In order to use it, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false` or remove spring-cloud-starter-netflix-ribbon from your project.
2023-09-16 21:55:52.416 INFO 21032 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'taskScheduler'
2023-09-16 21:55:52.423 INFO 21032 --- [ main] o.s.c.f.c.c.SimpleFunctionRegistry : Looking up function '' with acceptedOutputTypes: []
2023-09-16 21:55:52.530 INFO 21032 --- [ main] o.s.i.monitor.IntegrationMBeanExporter : Registering MessageChannel nullChannel
2023-09-16 21:55:52.539 INFO 21032 --- [ main] o.s.i.monitor.IntegrationMBeanExporter : Registering MessageChannel errorChannel
2023-09-16 21:55:52.568 INFO 21032 --- [ main] o.s.i.monitor.IntegrationMBeanExporter : Registering MessageHandler errorLogger
2023-09-16 21:55:52.585 INFO 21032 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2023-09-16 21:55:52.585 INFO 21032 --- [ main] o.s.i.channel.PublishSubscribeChannel : Channel 'async-service-1.errorChannel' has 1 subscriber(s).
2023-09-16 21:55:52.585 INFO 21032 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started bean '_org.springframework.integration.errorLogger'
2023-09-16 21:55:52.589 INFO 21032 --- [ main] o.s.c.n.eureka.InstanceInfoFactory : Setting initial instance status as: STARTING
2023-09-16 21:55:52.605 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Initializing Eureka in region us-east-1
2023-09-16 21:55:52.634 INFO 21032 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON encoding codec LegacyJacksonJson
2023-09-16 21:55:52.634 INFO 21032 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON decoding codec LegacyJacksonJson
2023-09-16 21:55:52.697 INFO 21032 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML encoding codec XStreamXml
2023-09-16 21:55:52.697 INFO 21032 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML decoding codec XStreamXml
2023-09-16 21:55:52.795 INFO 21032 --- [ main] c.n.d.s.r.aws.ConfigClusterResolver : Resolving eureka endpoints via configuration
2023-09-16 21:55:53.015 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Disable delta property : false
2023-09-16 21:55:53.015 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Single vip registry refresh property : null
2023-09-16 21:55:53.015 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Force full registry fetch : false
2023-09-16 21:55:53.015 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Application is null : false
2023-09-16 21:55:53.015 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Registered Applications size is zero : true
2023-09-16 21:55:53.015 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Application version is -1: true
2023-09-16 21:55:53.015 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Getting all instance registry info from the eureka server
2023-09-16 21:55:53.073 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : The response status is 200
2023-09-16 21:55:53.075 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Starting heartbeat executor: renew interval is: 30
2023-09-16 21:55:53.076 INFO 21032 --- [ main] c.n.discovery.InstanceInfoReplicator : InstanceInfoReplicator onDemand update allowed rate per min is 4
2023-09-16 21:55:53.078 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Discovery Client initialized at timestamp 1694872553077 with initial instances count: 1
2023-09-16 21:55:53.078 INFO 21032 --- [ main] o.s.c.n.e.s.EurekaServiceRegistry : Registering application MANAGE-ASYNC with eureka with status UP
2023-09-16 21:55:53.079 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Saw local status change event StatusChangeEvent [timestamp=1694872553079, current=UP, previous=STARTING]
2023-09-16 21:55:53.079 INFO 21032 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_MANAGE-ASYNC/NAMEL:manage-async:8090: registering service...
2023-09-16 21:55:53.093 INFO 21032 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8090 (http) with context path ''
2023-09-16 21:55:53.094 INFO 21032 --- [ main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8090
2023-09-16 21:55:53.105 INFO 21032 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_MANAGE-ASYNC/NAMEL:manage-async:8090 - registration status: 204
2023-09-16 21:55:53.406 WARN 21032 --- [ main] ConfigServletWebServerApplicationContext : 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 'config.value' in value "${config.value}"
2023-09-16 21:55:53.406 INFO 21032 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Removing {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2023-09-16 21:55:53.406 INFO 21032 --- [ main] o.s.i.channel.PublishSubscribeChannel : Channel 'async-service-1.errorChannel' has 0 subscriber(s).
2023-09-16 21:55:53.406 INFO 21032 --- [ main] o.s.i.endpoint.EventDrivenConsumer : stopped bean '_org.springframework.integration.errorLogger'
2023-09-16 21:55:53.406 INFO 21032 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService 'taskScheduler'
2023-09-16 21:55:53.410 INFO 21032 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2023-09-16 21:55:53.412 INFO 21032 --- [ main] o.s.i.monitor.IntegrationMBeanExporter : Summary on shutdown: nullChannel
2023-09-16 21:55:53.412 INFO 21032 --- [ main] o.s.i.monitor.IntegrationMBeanExporter : Summary on shutdown: bean 'errorChannel'
2023-09-16 21:55:53.412 INFO 21032 --- [ main] o.s.i.monitor.IntegrationMBeanExporter : Summary on shutdown: bean '_org.springframework.integration.errorLogger.handler' for component '_org.springframework.integration.errorLogger'
2023-09-16 21:55:53.412 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Shutting down DiscoveryClient ...
2023-09-16 21:55:56.427 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Unregistering ...
2023-09-16 21:55:56.445 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : DiscoveryClient_MANAGE-ASYNC/NAMEL:manage-async:8090 - deregister status: 200
2023-09-16 21:55:56.449 INFO 21032 --- [ main] com.netflix.discovery.DiscoveryClient : Completed shut down of DiscoveryClient
2023-09-16 21:55:56.663 INFO 21032 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2023-09-16 21:55:56.681 INFO 21032 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2023-09-16 21:55:56.689 ERROR 21032 --- [ main] o.s.boot.SpringApplication : 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 'config.value' in value "${config.value}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1420) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$1(AbstractBeanFactory.java:363) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.cloud.context.scope.GenericScope$BeanLifecycleWrapper.getBean(GenericScope.java:389) ~[spring-cloud-context-2.2.6.RELEASE.jar:2.2.6.RELEASE]
at org.springframework.cloud.context.scope.GenericScope.get(GenericScope.java:186) ~[spring-cloud-context-2.2.6.RELEASE.jar:2.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:360) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109) ~[spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.cloud.context.scope.refresh.RefreshScope.eagerlyInitialize(RefreshScope.java:127) ~[spring-cloud-context-2.2.6.RELEASE.jar:2.2.6.RELEASE]
at org.springframework.cloud.context.scope.refresh.RefreshScope.start(RefreshScope.java:118) ~[spring-cloud-context-2.2.6.RELEASE.jar:2.2.6.RELEASE]
at org.springframework.cloud.context.scope.refresh.RefreshScope.onApplicationEvent(RefreshScope.java:112) ~[spring-cloud-context-2.2.6.RELEASE.jar:2.2.6.RELEASE]
at org.springframework.cloud.context.scope.refresh.RefreshScope.onApplicationEvent(RefreshScope.java:66) ~[spring-cloud-context-2.2.6.RELEASE.jar:2.2.6.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404) ~[spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361) ~[spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:898) ~[spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:554) ~[spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:405) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.7.RELEASE.jar:2.3.7.RELEASE]
at com.nameli.async.ManageAsyncApplication.main(ManageAsyncApplication.java:20) [classes/:na]
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'config.value' in value "${config.value}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175) ~[spring-context-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:918) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
... 28 common frames omitted
2023-09-16 21:55:56.690 WARN 21032 --- [ Thread-3] c.a.n.common.http.HttpClientBeanHolder : [HttpClientBeanHolder] Start destroying common HttpClient
2023-09-16 21:55:56.690 WARN 21032 --- [ Thread-3] c.a.n.common.http.HttpClientBeanHolder : [HttpClientBeanHolder] Destruction of the end
Process finished with exit code 1
错误原因有以下几种
1:本地bootstrap.yml配置文件和nacos服务端配置的不一致(检查后发现是一致的)
名称一致,类型正确。
2: @Value注解是否有拼写错误,检查后发现无错误
3:是否缺少相应的maven依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
<version>4.0.0</version>
</dependency>
4:如果是使用Eureka作为注册中心的,检查application.yml文件下的spring.application.name和bootstrap.yml里spring.application.name是否一致
截止到此,SpringCloud简单集成nacos已经完成了,至于程序运行启动时返回的 Could not resolve placeholder ‘config.value’ in value “${config.value}” 我这里是第四点没有保持一致导致的,将两个yml文件里的name保持一致后,程序即可正常运行并且成功通过nacos获取配置文件的属性值信息。
上面这篇文章是我在搭建自己的微服务过程中出现的问题,如果这篇文章有什么错误之处,欢迎大佬指正!感谢!