配置中心在使用上和注册中心有些相似之处,也是分为客户端和服务端,服务端用来连接我们的远程仓库(如git、svn)获取仓库中的配置文件,客户端连接服务端,从服务端获取配置文件信息。
服务端:
1、添加maven依赖
<!--启动项目使用-->
<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>
<!--指定向eurekaServer上注册自己,也可以不注册-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2、添加yml配置
spring:
application:
name: config-server
cloud:
config:
server:
#使用git作为远程仓库
git:
#这里是你远程仓库配置文件的地址
uri: https://github.com/***/***
username:
password:
timeout: 15
#启用config配置
discovery:
enabled: true
server:
port: 8100
eureka:
instance:
hostname: config-server
instance-id: config-server
client:
service-url:
defaultZone: http://eurekaServer:8700/eurekaServer/eureka
3、启动类上添加注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableConfigServer
@EnableEurekaClient
@SpringBootApplication
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
git仓库:
configServer获取文件信息:
PS:config对获取配置文件有格式要求文件名要以 {preName}-{suffixName}.yml 这样的格式才能获取到。
PS:服务端每次请求都会获取到远程仓库最新的信息。服务端启动的时候不会获取远程仓库的信息,只在我们调用服务端的时候服务端才会去远程仓库获取信息。
全路径:http://host:port/枝干/文件名称
枝干:默认是master,如果请求中不加枝干就是master,添加的话指定好即可。
如http://xxxx:xx/dev/ {preName}-{suffixName}.yml
获取的就是远程仓库中dev分支上的{preName}-{suffixName}.yml的信息。
获取文件类型:.properties .json .yml