一.简介
SpringCloudConfig是微服务的配置中心,使用git/svn 作为版本管理工具管理配置文件,这样所有的微服务都通过SpringCloudConfig微服务动态获取配置信息。
SpringCloudConfig 微服务注册到Eureka中,而后所有微服务都从SpringCloudConfig微服务中获取配置。
二.SpringCloudConfig微服务端
1.编写服务端配置文件并推送到git
server:
port: 8001
context-path: /service-user
spring:
application:
name: service-user
eureka:
client:
service-url:
defaultZone: http://localhost:7001/service-eureka/eureka
2.新建config-server作为配置服务端微服务
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
3.application.yml配置文件
server:
port: 8501
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: https://gitee.com/vincent-java-test/spring-cloud-profiles.git
username: xxxxxx #git 登录用户名
password: xxxxx #git 登录密码
eureka:
client:
service-url:
defaultZone: http://localhost:7001/service-eureka/eureka
4.编写启动类
package com.vincent;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
@EnableConfigServer
public class ConfigApp {
public static void main(String[] args) {
SpringApplication.run(ConfigApp.class,args);
}
}
5.启动微服务
通过以下形式访问git中的配置文件:{label}/{application}-{profile}.yml
http://localhost:8501/master/service-user-prod.yml
三.从配置微服务获取配置信息
1.服务端引入配置依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
2.服务端微服务新建bootstrap.yml 文件
spring:
cloud:
config:
uri: http://localhost:8501
#配置文件所在分支
label: master
#配置文件资源文件名称
name: service-user
#配置文件profile
profile: prod
application.yml 属于用户级资源配置,bootstrap.yml属于系统级资源配置,其优先级更高。
3.启动服务端微服务时会从从配置微服务中获取配置信息
4.通过消费端访问服务端:http://localhost:9001/detail?id=1
四.SpringCloudConfig高可用
如果SpringCloudConfig服务出现问题则所有微服务都将瘫痪,SpringCloudConfig高可用机制可以避免单主机缺陷。
1.SpringCloudConfig服务新增8502端口服务
2.修改服务端bootstrap.yml
spring:
cloud:
config:
label: master
name: service-user
profile: prod
discovery: #使用服务注册中心服务名称代替ip:port
enabled: true
service-id: config-server
eureka:
client:
service-url:
defaultZone: http://localhost:7001/service-eureka/eureka
3.启动服务端、消费端应用,访问:http://localhost:9001/detail?id=1