Config
创建一个config server
pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
application.properties
spring.application.name=config-server
server.port=8888
spring.cloud.config.server.git.uri=https://github.com/forezp/SpringcloudConfig/ //仓库地址
spring.cloud.config.server.git.searchPaths=respo //仓库路径
spring.cloud.config.label=master //仓库分支
spring.cloud.config.server.git.username=
spring.cloud.config.server.git.password=
@EnableConfigServer
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
测试
远程仓库https://github.com/forezp/SpringcloudConfig/ 中准备一个文件:
config-client-dev.properties,内容:foo = foo version 3
访问http://localhost:8888/foo/dev
返回结果:
{"name":"foo","profiles":["dev"],"label":"master", "version":"792ffc77c03f4b138d28e89b576900ac5e01a44b","state":null,"propertySources":[]}
创建一个config client
pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
配置文件bootstrap.properties
spring.application.name=config-client
spring.cloud.config.label=master // 远程仓库分支
spring.cloud.config.profile=dev // dev:开发环境 test:测试 pro:生产
spring.cloud.config.uri= http://localhost:8888 // 指明配置服务中心地址
server.port=8881
@Value("${foo}"
@SpringBootApplication
@RestController
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
@Value("${foo}")
String foo;
@RequestMapping(value = "/hi")
public String hi(){
return foo;
}
}
集群(高可用的分布式配置中心)
修改config server
eureka.client.serviceUrl.defaultZone=http://localhost:8889/eureka/
修改config client
spring.application.name=config-client
spring.cloud.config.label=master
spring.cloud.config.profile=dev
#spring.cloud.config.uri= http://localhost:8888/
eureka.client.serviceUrl.defaultZone=http://localhost:8889/eureka/
spring.cloud.config.discovery.enabled=true //从配置中心读
spring.cloud.config.discovery.serviceId=config-server //config服务名
server.port=8881