在微服务开发过程中,为了保证我们服务的高可用,不可避免的需要配置多台服务器组成集群,而集群中每一台主机的配置文件都是相同的,对配置文件的更新维护就成为了一个棘手的问题,针对于该问题,spring cloud官方给出了一个解决方案,使用Spring Cloud Config配置中心来管理所有的配置文件。
原理
Spring Cloud Config 就是对微服务的配置文件进行统一管理的。其工作原理是,我们首先需要将各个微服务公共的配置信息推送到 GitHub 远程版本库。然后我们再定义一个 Spring Cloud Config Server,其会连接上这个 GitHub 远程库。这样我们就可以定义 Config 版的 Eureka Server、提供者与消费者了,它们都将作为 Spring Cloud Config Client 出现,它们都会通过连接 Spring Cloud Config Server 连接上 GitHub 上的远程库,以读取到指定配置文件中的内容。
快速体验
1. Eureka服务端
<!-- eureka服务端依赖 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> |
application.yml
server: port: 10080 spring: application: name: eureka-server eureka: client: service-url: defaultZone: http://127.0.0.1:10000/eureka register-with-eureka: false fetch-registry: false |
启动类
@SpringBootApplication @EnableEurekaServer public class EurekaServerApp { public static void main(String[] args) { SpringApplication.run(EurekaServerApp.class, args); } } |
2. spring cloud config
<!-- eureka client --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- spring cloud config --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> |
application.yml
server: port: 10010 spring: application: name: config-server cloud: config: server: git: uri: ${git仓库地址} default-label: master timeout: 5 #若网络需要代理配置,则加上proxy配置 #proxy: # https: # host: # port: # username: # password: username: ${git用户名} password: ${git密码} eureka: client: service-url: defaultZone: http://127.0.0.1:10080/eureka instance: prefer-ip-address: true ip-address: 127.0.0.1 |
启动类
@SpringBootApplication @EnableConfigServer public class ConfigServerApp { public static void main(String[] args) { SpringApplication.run(ConfigServerApp.class, args); } } |
spring cloud config 客户端
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> |
application.yml
spring: cloud: config: name: bill-server #与git中的配置文件application名一致 profile: dev label: master discovery: enabled: true service-id: config-server #服务名 eureka: client: service-url: defaultZone: http://127.0.0.1:10080/eureka register-with-eureka: true fetch-registry: true instance: ip-address: 127.0.0.1 prefer-ip-address: true management: endpoints: web: exposure: include: bus-refresh |
启动类
@SpringBootApplication @EnableEurekaClient public class BillServerApp { public static void main(String[] args) { SpringApplication.run(BillServerApp.class, args); } } |
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理