概述
本文将继续介绍的是SpringCloud中的分布式配置中心Config的相关使用教程。Spring Cloud Config项目是一个解决分布式系统的配置管理方案。它包含了Client和Server两个部分,server提供配置文件的存储、以接口的形式将配置文件的内容提供出去,client通过接口获取数据、并依据此数据初始化自己的应用。
服务端Server
pom依赖包配置
<dependencies>
<!--配置中心 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<!--web 模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--eureka 客户端 -->
<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-netflix-hystrix</artifactId>
</dependency>
<!--配置文件处理器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
启动类
@EnableConfigServer
@SpringCloudApplication
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
bootstrap.yml配置文件
server:
port: 8888
spring:
application:
name: demo-config
profiles:
active: native
# 配置中心
cloud:
config:
server:
native:
search-locations: file:config/
# 注册中心
eureka:
client:
serviceUrl:
defaultZone: ${EUREKA_SERVICE_URL:http://demo:123456@fams-eureka:8761/eureka/}
registry-fetch-interval-seconds: 10
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 10
lease-expiration-duration-in-seconds: 15
instanceId: ${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}}
配置文件路径放在 项目路径/config 下。
客户端Client
bootstrap.yml配置文件
server:
port: 8089
spring:
application:
name: demo-service
profiles:
active: dev
cloud:
config:
fail-fast: true
name: ${spring.application.name}
profile: ${spring.profiles.active}
discovery:
enabled: true
service-id: demo-config
# 注册中心
eureka:
client:
serviceUrl:
defaultZone: ${EUREKA_SERVICE_URL:http://demo:123456@localhost:8761/eureka/}
启动后,就会从demo-config中尝试获取 demo-service-dev.yml 配置文件。