近两年微服务Spring Cloud 受到众多公司的喜爱;很多公司由单体项目往微服务转移;在微服务架构中,要管理好每个服务各自的配置信息是不那么容易的;Spring Cloud 为统一管理配置文件提供了Spring Cloud Config。
什么是Spring Cloud Config
Spring Cloud Config是Spring Cloud创建的一个全新的项目,用来分布式系统的基础设施和微服务应用提供集中化的外部配置的支持,它分为客户端和服务两部分。
使用Spring Cloud Config 好处
如果微服务架构中没有使用统一配置中心时,所存在的问题:
配置文件分散在各个项目里,不方便维护
配置内容安全与权限,实际开发中,开发人员是不知道线上环境的配置的
更新配置后,项目需要重启
使用配置中心后,这些问题都迎刃而解了。
Spring Cloud Config 实战
1)git 服务器创建存放配置文件的项目
在folder文件夹下新建neo-config-dev.properties,neo-config-test.properties,
里面存放的内容分别为hello–dev,hello-test.
- 新建Config 服务端引用
需要引用的jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--动态刷新-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--mq-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
在启动类使用 @EnableConfigServer 注解标识是 Config 服务端
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
application.yml 配置
spring:
application:
name: config-server
cloud:
config:
server:
git:
# git url
uri: https://github.com/younijiuxing/hello-config
# 配置文件所在的文件夹,需要被扫描后,才能获取到文件的配置
search-paths: folder
# 公开库不需要设置用户名和密码
username:
passphrase:
server:
port: 7001
# 这里也是必须要关闭的
management:
security:
enabled: false
3)搭建mq服务(以便后面动态数据刷新)
搭建mq比较简单,这里就不描述了。。。
4)客户端的新建
依赖的jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--动态刷新-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
将配置文件application.yml 修改为bootstrap.yml
修改内容:
spring:
cloud:
config:
name: neo-config
profile: dev
uri: http://localhost:7001/
label: master
application:
name: config-client
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
server:
port: 7002
management:
security:
enabled: false
在客户端创造一个接口,去访问我们git上的数据,如下图:
@RestController
@RefreshScope // 此注解为后面动态刷新很重要
public class HelloController {
@Value("${env}")
String message;
@RequestMapping("/hello")
public String sayHello(){
return "我是"+message+"环境";
}
}
通过http://localhost:7002/hello 去访问,
如果想让Spring Cloud Config 动态刷新,可以在git的URL。