微服务-注册中心与网关 学习完引出来新的问题:配置太多,无法统一管理
现在用nacos来管理看看
1. 环境
| 中间件 | 作用 | 备考 |
|---|---|---|
| nacos | 配置中心 | 简单安装方式 |
2. 配置中心(nacos)
应用nacos-group:github.com/nacos-group…
2.1 下载 nacos-docker
2.2 安装集群环境
nacos> docker-compose -f example/cluster-hostname.yaml up -d
Creating network "example_default" with the default driver
Creating mysql ... done
Creating nacos2 ... done
Creating nacos1 ... done
Creating nacos3 ... done
2.3 查看一下管理平台
3. 配置中心
3.1 首先构建开发环境(dev)和生产环境(prd)命名空间
3.2 其次把之前的配置存在这里
3.3 代码层的修改(spring-cloud-provider)
pom.xml中追加如下依赖
......
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.7</version>
</dependency>
.....
启动类 SpringCloudProviderApplication.java
package com.cloud.provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
@SpringBootApplication
//支持服务发现
@EnableDiscoveryClient
//支持配置中心
@NacosPropertySource(dataId="spring-cloud-provider-01.properties", autoRefreshed = true, groupId = "USER_GROUP")
public class SpringCloudProviderApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudProviderApplication.class, args);
}
}
@NacosPropertySource(dataId="spring-cloud-provider-01.properties", autoRefreshed = true, groupId = "USER_GROUP") 这里要和3.2 的内容匹配起来
配置文件
application-dev.properties
# nacos认证信息
spring.cloud.nacos.config.username=nacos
spring.cloud.nacos.config.password=nacos
#spring.cloud.nacos.config.contextPath=/nacos
spring.cloud.nacos.config.namespace=e5c3cda1-52a5-4328-a21c-f556ebe0d20f
# ----------配置中心,如果无需使用配置中心,可以删除此部分配置----------
# 设置配置中心服务端地址
spring.cloud.nacos.config.server-addr= localhost:8848
application-prd.properties
# nacos认证信息
spring.cloud.nacos.config.username=nacos
spring.cloud.nacos.config.password=nacos
#spring.cloud.nacos.config.contextPath=/nacos
spring.cloud.nacos.config.namespace=41435ed9-0edf-4c44-aaf6-727b67816681
# ----------配置中心,如果无需使用配置中心,可以删除此部分配置----------
# 设置配置中心服务端地址
spring.cloud.nacos.config.server-addr= localhost:8848
这部分只需与nacos的命名空间及server地址对应起来就可以
3.4 启动服务看看
3.4.1 IDE环境
启动日志如下:
2021-02-20 23:34:31.078 INFO 13740 --- [ restartedMain] c.a.b.n.c.u.NacosConfigPropertiesUtils : nacosConfigProperties : NacosConfigProperties{serverAddr='127.0.0.1:8848', contextPath='null', encode='null', endpoint='null', namespace='null', accessKey='null', secretKey='null', ramRoleName='null', autoRefresh=false, dataId='null', dataIds='null', group='DEFAULT_GROUP', type=null, maxRetry='null', configLongPollTimeout='null', configRetryTime='null', enableRemoteSyncConfig=false, extConfig=[], bootstrap=Bootstrap{enable=false, logEnable=false}}
2021-02-20 23:34:31.081 INFO 13740 --- [ restartedMain] NacosConfigApplicationContextInitializer : [Nacos Config Boot] : The preload configuration is not enabled
2021-02-20 23:34:31.128 INFO 13740 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-02-20 23:34:31.286 INFO 13740 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$9a5367b7] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.8.RELEASE)
2021-02-20 23:34:33.374 INFO 13740 --- [ restartedMain] c.a.b.n.c.u.NacosConfigPropertiesUtils : nacosConfigProperties : NacosConfigProperties{serverAddr='127.0.0.1:8848', contextPath='null', encode='null', endpoint='null', namespace='null', accessKey='null', secretKey='null', ramRoleName='null', autoRefresh=false, dataId='null', dataIds='null', group='DEFAULT_GROUP', type=null, maxRetry='null', configLongPollTimeout='null', configRetryTime='null', enableRemoteSyncConfig=false, extConfig=[], bootstrap=Bootstrap{enable=false, logEnable=false}}
2021-02-20 23:34:33.374 INFO 13740 --- [ restartedMain] NacosConfigApplicationContextInitializer : [Nacos Config Boot] : The preload configuration is not enabled
2021-02-20 23:34:33.374 INFO 13740 --- [ restartedMain] c.c.p.SpringCloudProviderApplication : The following profiles are active: dev
2021-02-20 23:34:34.120 WARN 13740 --- [ restartedMain] o.s.boot.actuate.endpoint.EndpointId : Endpoint ID 'service-registry' contains invalid characters, please migrate to a valid format.
2021-02-20 23:34:34.247 INFO 13740 --- [ restartedMain] o.s.cloud.context.scope.GenericScope : BeanFactory id=469cb250-9045-3f94-b685-af5a683c222c
2021-02-20 23:34:34.320 INFO 13740 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$9a5367b7] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-02-20 23:34:34.722 INFO 13740 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9001 (http)
2021-02-20 23:34:34.737 INFO 13740 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-02-20 23:34:34.737 INFO 13740 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.24]
2021-02-20 23:34:34.901 INFO 13740 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-02-20 23:34:34.901 INFO 13740 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1516 ms
2021-02-20 23:34:35.026 WARN 13740 --- [ restartedMain] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2021-02-20 23:34:35.026 INFO 13740 --- [ restartedMain] 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.
2021-02-20 23:34:35.030 INFO 13740 --- [ restartedMain] c.netflix.config.DynamicPropertyFactory : DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration@4f1ceb40
2021-02-20 23:34:38.390 INFO 13740 --- [ restartedMain] o.s.cloud.commons.util.InetUtils : Cannot determine local hostname
2021-02-20 23:34:38.629 WARN 13740 --- [ restartedMain] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2021-02-20 23:34:38.629 INFO 13740 --- [ restartedMain] 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.
2021-02-20 23:34:38.829 INFO 13740 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-02-20 23:34:39.208 INFO 13740 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-02-20 23:34:41.219 INFO 13740 --- [ restartedMain] o.s.cloud.commons.util.InetUtils : Cannot determine local hostname
2021-02-20 23:34:41.324 INFO 13740 --- [ restartedMain] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'catalogWatchTaskScheduler'
2021-02-20 23:34:41.339 INFO 13740 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2021-02-20 23:34:41.373 INFO 13740 --- [on(2)-127.0.0.1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-02-20 23:34:41.374 INFO 13740 --- [on(2)-127.0.0.1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-02-20 23:34:41.390 INFO 13740 --- [on(2)-127.0.0.1] o.s.web.servlet.DispatcherServlet : Completed initialization in 16 ms
2021-02-20 23:34:41.420 INFO 13740 --- [ restartedMain] .LoggingNacosConfigMetadataEventListener : Nacos Config Metadata : dataId='spring-cloud-provider-01.properties', groupId='USER_GROUP', beanName='springCloudProviderApplication', bean='null', beanType='class com.cloud.provider.SpringCloudProviderApplication', annotatedElement='null', xmlResource='null', nacosProperties='{maxRetry=${nacos.config.maxRetry${nacos.maxRetry:}}, configRetryTime=${nacos.config.configRetryTime${nacos.configRetryTime:}}, serverAddr=127.0.0.1:8848, encode=UTF-8, configLongPollTimeout=${nacos.config.configLongPollTimeout${nacos.configLongPollTimeout:}}, enableRemoteSyncConfig=false}', nacosPropertiesAttributes='{encode=${nacos.encode:UTF-8}, namespace=${nacos.namespace:}, enableRemoteSyncConfig=${nacos.enableRemoteSyncConfig:}, configLongPollTimeout=${nacos.configLongPollTimeout:}, serverAddr=${nacos.server-addr:}, secretKey=${nacos.secret-key:}, configRetryTime=${nacos.configRetryTime:}, maxRetry=${nacos.maxRetry:}, username=${nacos.username:}, contextPath=${nacos.context-path:}, endpoint=${nacos.endpoint:}, password=${nacos.password:}, accessKey=${nacos.access-key:}, clusterName=${nacos.cluster-name:}}', source='org.springframework.core.type.StandardAnnotationMetadata@2a8725ac', timestamp='1613831673959'
2021-02-20 23:34:41.452 INFO 13740 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9001 (http) with context path ''
2021-02-20 23:34:41.459 INFO 13740 --- [ restartedMain] o.s.c.c.s.ConsulServiceRegistry : Registering service with consul: NewService{id='spring-cloud-provider-01-9001', name='service-provider', tags=[secure=false], address='192.168.8.1', meta=null, port=9001, enableTagOverride=null, check=Check{script='null', interval='10s', ttl='null', http='http://192.168.8.1:9001/actuator/health', method='null', header={}, tcp='null', timeout='null', deregisterCriticalServiceAfter='null', tlsSkipVerify=null, status='null'}, checks=null}
2021-02-20 23:34:43.453 INFO 13740 --- [ restartedMain] o.s.cloud.commons.util.InetUtils : Cannot determine local hostname
2021-02-20 23:34:43.455 INFO 13740 --- [ restartedMain] c.c.p.SpringCloudProviderApplication : Started SpringCloudProviderApplication in 14.651 seconds (JVM running for 15.891)
3.4.2 查看Consul
3.4.3 浏览器访问
3.5 命令行访问方式
命令行
java -jar spring-cloud-provider-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
gitee:gitee.com/actual-comb…
4 结论
所有微服务只需连接配置中心就可
切换环境也很便捷:-Dspring.profiles.active=[环境变量]
以前管理混乱的Spring老大难的配置问题就这样解决了