接上一章节构建 Springcloud config 配置中心,这里讲讲构建 Springcloud config 配置中心仓库及客户端
接下来我们需要在 gitee 上设置好配置中心,首先在本地创建一个文件夹叫springcloudconfig,然后在里面创建一个文件夹叫 config-center,然后在 config-center中创建四个配置文件,如下:
application.properties
application-dev.properties
application-test.properties
application-online.properties
在四个文件里面分别写上要测试的内容:
url=http://www.lixuanhong.com
url=http://dev.lixuanhong.com
url=http://test.lixuanhong.com
url=http://online.lixuanhong.com
然后回到 springcloudconfig目录下,将本地文件同步到 gitee 仓库中(如果将本地文件提交到gitee上):
至此,我们的配置文件就上传到 gitee 上了。
此时启动我们的配置中心,通过/{application}/{profile}/{label}就能访问到我们的配置文件了;
其中:
{application} 表示配置文件的名字,对应的配置文件即 application,
{profile} 表示环境,有 dev、test、online 及默认,
{label} 表示分支,默认我们放在 master 分支上,
通过浏览器上访问 http://localhost:3731/application/dev/master 返回的 JSON 格式的数据:
name 表示配置文件名 application 部分,
profiles 表示环境部分,
label 表示分支,
version 表示 GitHub 上提交时产生的版本号,
同时当我们访问成功后,在控制台会打印了相关的日志信息;
当访问成功后配置中心会通过 git clone 命令将远程配置文件在本地也保存一份,以确保在 git 仓库故障时我们的应用还可以继续正常使用。
1、创建一个普通的 Spring Boot 工程
2、添加相关依赖
org.springframework.cloud spring-cloud-starter-config org.springframework.boot spring-boot-starter-actuator org.springframework.cloud spring-cloud-starter-bootstrap org.springframework.cloud spring-cloud-dependencies 2021.0.3 pom import spring-milestones Spring Milestones https://repo.spring.io/libs-milestone false
3、创建 bootstrap.properties 文件,用于获取配置信息,文件内容如下:
(注意这些信息一定要放在 bootstrap.properties 文件中才有效)
server.port=3732
#name 对应配置文件中的 application 部分
spring.application.name=application
#profile 对应了 profile 部分
spring.cloud.config.profile=dev
#label 对应了 label 部分
spring.cloud.config.label=master
#uri 表示配置中心的地址
spring.cloud.config.uri=http://localhost:3731/
4、创建一个 Controller 进行测试:
@RestController
@RefreshScope
public class ConfigController {@Value("${url}")private String url;@RequestMapping("/cloud/url")public String url () {return this.url;}}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RefreshScope
public class ConfigController {@Value("${url}")private String url;@Autowiredprivate Environment env;@RequestMapping("/cloud/url")public String url () {return this.url;}@RequestMapping("/cloud/url2")public String url2 () {return env.getProperty("url");}}