从Spring cloud 的中文网开始,学习Spring cloud 的基础。
链接:https://springcloud.cc/spring-cloud-dalston.html#_spring_cloud_config
首先,先看一下spring 官网给的 Spring could 的结构图,如下所示:
从图中可见,Spring could config 用于管理breaker, micro services 的配置。知道了config 要做的事,继续看中文手册:
Spring Cloud上下文:应用程序上下文服务
大概讲了一些 Spring 工程的基本配置及特性。以及 Spring Cloud Commons 抽象的一些配置功能。
对于一个刚入门的小白来说,没有具体的东西,看起来也是一头雾水。所以先跳过。直接下一个
Spring Cloud Config
Spring Cloud Config为分布式系统中的外部配置提供服务器和客户端支持。使用Config Server,您可以在所有环境中管理应用程序的外部属性。客户端和服务器上的概念映射与Spring Environment
和PropertySource
抽象相同。
先看官方的例子吧
http://spring.io/guides/gs/centralized-configuration/
Windows 装 git, 先把工程clone 下来。
git clone https://github.com/spring-guides/gs-centralized-configuration.git
以STS为例:
导入工程。
根据教程,需要将Config Server 指向一个Github or GitLab repository。
那么先在文件系统上创建一个目录,比如 D:\springConfig\config,在此目录中添加一个文件:a-bootiful-client.properties,然后初始化git并提交
git init
git commit -am "init"
you will connect to the Config Server with a Spring Boot application whose spring.application.name
property identifies it as a-bootiful-client
to the Config Server.
也就是说,客户端配置文件里的的 spring.application.name 必须是 a-bootiful-client。
打开客户端工程,在bootstrap.properties中可以看到。那么我们现在创建的文件,在系统启动后,将会替换原工程中的配置。
接下来,在a-bootiful-client.properties 中加一些配置:
message=Hello world
然后提交。
接下来,配置config server工程。
主要是把这个git 的地址配置起来。
一般是要配置一个服务器的地址。但是我自己本地也没有,只好用文件系统了(好像只能用这种写法)。如上所示:
然后我们看看效果:
1.先启动server,
2.再启动client.
启动好了之前。打开浏览器,
看到 Hello world。 就表示成功了。
通常,配置项仅在工程启动的时候才会加载。如果改了配置,想要不停服务动态刷新怎么办呢?
1. 先加入以下依赖。(Spring 给的例子工程中,client 工程已经有了)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
然后再以 post 的方式调用 刷新的地址 http://localhost:8080/actuator/refresh
我们试一试:
1.先修改a-bootiful-client.properties 的message
message=Welcome to spring cloud config
本地文件,不用提交也可以。
2. 刷新一下。可以使用postman:
3. 接下来,看看效果。