新建 kitty-conifg 工程,作为配置中心的服务端,负责把GIT仓库的配置文件发布为RESTFul接口
添加依赖除了Spring Cloud依赖之外,添加配置中心依赖包。了解springcloud架构可以加求求:三五三六二四七二五九
pom.xml
启动类org.springframework.cloud spring-cloud-config-server
启动类添加注解 @EnableConfigServer,开启配置服务支持。
KittyConfigApplication.java
package com.louis.kitty.config;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.config.server.EnableConfigServer;
@EnableConfigServer
@EnableDiscoveryClient
@SpringBootApplicationpublic class KittyConfigApplication { public static void main(String[] args) {
SpringApplication.run(KittyConfigApplication.class, args);
}
}配置文件修改配置文件,添加如下内容。如果是私有仓库需要填写用户名密码,如果是公开仓库,可以不配置密码。
application.yml
server:
port: 8020spring:
application:
name: kitty-config
cloud:
consul:
host: localhost
port: 8500
discovery:
serviceName: ${spring.application.name} # 注册到consul的服务名称
config:
label: master # git仓库分支
server:
git:
uri: https://gitee.com/liuge1988/kitty.git # 配置git仓库的地址
search-paths: config-repo # git仓库地址下的相对地址,可以配置多个,用,分割。
username: username # git仓库的账号
password: password # git仓库的密码Spring Cloud Config也提供本地存储配置的方式,只需设置属性spring.profiles.active=native,Config Server会默认从应用的src/main/resource目录下检索配置文件。另外也可以通过spring.cloud.config.server.native.searchLocations=file:D:/properties/属性来指定配置文件的位置。虽然Spring Cloud Config提供了这样的功能,但是为了更好的支持内容管理和版本控制,还是比较推荐使用GIT的方式。
测试效果启动注册中心,配置中心,访问 http://localhost:8020/kitty-consumer/dev,返回结果如下。
{ "name": "kitty-consumer", "profiles": ["dev"], "label": null, "version": "1320259308dfdf438f5963f95cbce9e0a76997b7", "state": null, "propertySources": [{ "name": "https://gitee.com/liuge1988/kitty.git/config-repo/kitty-consumer-dev.properties", "source": { "consumer.hello": "hello, this is dev configurations. "
}
}]
}访问 http://localhost:8020/kitty-consumer/pro,返回结果如下。
{ "name": "kitty-consumer", "profiles": ["pro"], "label": null, "version": "1320259308dfdf438f5963f95cbce9e0a76997b7", "state": null, "propertySources": [{ "name": "https://gitee.com/liuge1988/kitty.git/config-repo/kitty-consumer-pro.properties", "source": { "consumer.hello": "hello, this is pro configurations. "
}
}]
}上述的返回的信息包含了配置文件的位置、版本、配置文件的名称以及配置文件中的具体内容,说明server端已经成功获取了git仓库的配置信息。



