常见的配置中心的实现方法有:
SpringCloud中提供了分布式配置中Spring Cloud Config,为外部配置提供了客户端和服务器端的支持。基于Config服务器,就可以集中管理各种环境下的各种应用的配置信息。其中,将包括两个部分:配置服务器和配置客户端。Config Server即是配置服务器,为客户端提供其对应的配置信息,配置信息的来源为配置仓库,启动时需要拉取配置仓库的信息,储存到本地仓库中; Config Client客户端,只会在本 配置必要的信息,如指定获取配置的Config Server地址,启动时从配置服务器获取配置信息,并支持动态刷新配置仓库中的属性值。
创建一个spring-boot项目,取名为config-server,添加maven依赖。
org.springframework.boot spring-boot-starter-web
org.springframework.cloud spring-cloud-config-server
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {public static void main(String[] args) {SpringApplication.run(ConfigServerApplication.class, args);}}
server:port: 8500
spring:cloud:config:server:git:uri: https://github.com/fengfangithub/study-springcloud.gitsearch-paths: springcloud-configdefault-label: masterusername:password:
config.name=myconfig
config.age=18
Spring Cloud Config有它的一套访问规则,我们通过这套规则在浏览器上直接访问就可以。
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
创建一个spring-boot项目,取名为config-client,添加maven依赖。
org.springframework.boot spring-boot-starter-web
org.springframework.cloud spring-cloud-starter-config
spring:application:name: config-clientcloud:config:uri: http://localhost:8500/ #配置服务地址label: masterprofile: dev
@RestController
@RequestMapping("/api")
public class ConfigPrintController {@Value("config.name")private String name;@Value("config.age")private int age;@PostMapping("/printConfig")public String printConfig(){return "name:" + name + ",age:" + age;}
}
配置中心可以做成一个微服务,将其集群化,从而达到高可用。其中注册中心还是沿用前面的eureka-serve,修改config-server、config-client
org.springframework.cloud spring-cloud-starter-netflix-eureka-client
server:port: 8500
spring:application:name: config-servercloud:config:server:git:uri: https://github.com/fengfangithub/study-springcloud.gitsearch-paths: springcloud-configdefault-label: masterusername: password: eureka:client:service-url:defaultZone: http://localhost:8761/eureka/instance:# 自定义服务名称信息instance-id: config-server:8500#访问路径可以显示Ip地址prefer-ip-address: true
和config-server一样配置到注册中心,这里不再重复。
spring:application:name: config-clientcloud:config:
# uri: http://localhost:8500/ #配置服务地址label: masterprofile: devdiscovery:enabled: true #从配置中心读取文件service-id: config-server #配置中心的servieId,即服务名。eureka:client:service-url:defaultZone: http://localhost:8761/eureka/instance:# 自定义服务名称信息instance-id: config-client:8600#访问路径可以显示Ip地址prefer-ip-address: true
下一篇:顶会中的对比学习论文