在springCloud中,每一个服务都需要一个application.yml配置文件 ,在进行修改的时候不便于集中管理。因此springcloud的配置中心应运而生。即我们将整个项目中的核心配置文件都放在云端(如github),我们通过配置中心去拿到配置文件,然后在分配给各个服务。
实现原理大概如下

建立一个配置中心模块,注册到注册中心
application.yml
server:
port: 2222
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka
instance:
prefer-ip-address: true
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: https://github.com/xxx/microservice-config.git #配置文件所在github位置
username: xxxx #用户名
password: xxxx #密码
入口类:
@SpringBootApplication
@EnableEurekaClient
@EnableConfigServer //表示是配置中心服务端
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class);
}
}
在服务者的配置文件配置bootstrap.xml,bootstrap.xml是全局配置
spring:
cloud:
config:
name: application-user #github上面名称
profile: test #环境
label: master #github分支
uri: http://127.0.0.1:2222 #配置服务器
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka #告诉服务提供者要把服务注册到哪儿 #单机环境
instance:
prefer-ip-address: true #显示客户端真实ip
服务者打印日志如下,并未在本地配置端口,但是通过配置中心访问到云端的配置文件了。
这样我们就可以访问到云端的配置文件了
2019-01-08 17:27:14.195 INFO 19040 --- [ main] o.s.c.n.e.s.EurekaServiceRegistry : Registering application MICROSERVICE-USER-TEST with eureka with status UP
2019-01-08 17:27:14.196 INFO 19040 --- [ main] com.netflix.discovery.DiscoveryClient : Saw local status change event StatusChangeEvent [timestamp=1546939634196, current=UP, previous=STARTING]
2019-01-08 17:27:14.201 INFO 19040 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_MICROSERVICE-USER-TEST/freebird:MICROSERVICE-USER-TEST:3355: registering service...
2019-01-08 17:27:14.272 INFO 19040 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_MICROSERVICE-USER-TEST/freebird:MICROSERVICE-USER-TEST:3355 - registration status: 204
2019-01-08 17:27:14.294 INFO 19040 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 3355 (http) with context path ''
2019-01-08 17:27:14.295 INFO 19040 --- [ main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 3355
2019-01-08 17:27:14.301 INFO 19040 --- [ main] c.i.springcloud.ProviderApplication : Started ProviderApplication in 17.802 seconds (JVM running for 21.336)
本文介绍了SpringCloud配置中心ConfigServer的使用,旨在解决多服务配置文件分散不便管理的问题。通过将配置文件存储于云端(如GitHub),服务通过ConfigServer获取并应用配置,实现集中化管理。配置中心的实现包括创建ConfigServer模块,将其注册到注册中心,配置application.yml和bootstrap.yml,从而让服务能够成功从云端读取配置。
168万+

被折叠的 条评论
为什么被折叠?



