写在前面
-
Spring Cloud Config是Spring创建的一个全新的服务端/客户端项目,为应用提供分布式的配置存储,提供集中化的外部配置支持。它除了适用于Spring构建的应用程序外,也可以在其他语言运行的应用程序中使用。
-
Spring Cloud Config分为服务端和客户端两部分。其中服务端称为分布式配置中心,用来连接配置仓库并为客户端提供获取配置信息、加密/解密信息的功能;客户端则是微服务架构中的各个微服务应用,它们通过指定的配置中心来管理与业务相关的配置内容,并在启动的时候从配置中心获取和加载配置信息。
-
Spring Cloud Config实现的配置中心默认采用Git来存储配置信息,但也提供了对其他存储方式的支持,比如SVN仓库、本地文件系统。在本例中构建了一个基于Git存储的分布式配置中心,并在客户端中演示了如何制定应用所属的配置中心,并能够从配置中心获取配置信息的整个过程。
搭建git服务器
- 创建用户 gitHub官网
- 新建项目 (git仓库)
测试配置中心环境
- 依赖管理
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
- main 方法
@SpringBootApplication
@EnableConfigServer
public class ConfigMain {
public static void main(String[] args) {
SpringApplication.run(ConfigMain.class,args);
}
}
- application.yml 文件
这里路径指向git仓库(配置中心)
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: https://github.com/用户名/configcentre
- 将uservice部署到GitHub仓库中
spring:
application:
name: uservice
profiles:
#环境切换
active: dev
# 配置中心 的ip和端口
# 这个文件等价于 http://localhost:8888/uservice-dev.yml
cloud:
config:
uri: http://localhost:8888
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
@SpringBootApplication
//启用微服务客户端
@EnableEurekaClient
@RestController
public class UserServiceMain {
public static void main(String[] args) {
new SpringApplicationBuilder(UserServiceMain.class).web(true).run(args);
}
}
测试
-
注册中心→配置中心→UserServiceMain → 依次启动
-
运行localhost:8888/uservice-dev.yml
效果如下
-
测试properties后缀,后缀不一样,格式不一样。
zuul
- 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
- main方法
@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class ZuulMain {
public static void main(String[] args) {
SpringApplication.run(ZuulMain.class);
//new SpringApplicationBuilder(ZuulMain.class).web(true).run(args);
}
}
- application.yml文件
将zuul部署到配置中心
eureka:
instance:
hostname: localhost
preferIpAddress: true
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://192.168.229.129:8761/eureka/
spring:
application:
name: zuul
server:
port: 88