SpringCloudConfig--ConfigServer从本地读取配置文件
ConfigServer从本地读取配置文件
Config Server可以从本地仓库读取配置文件,也可以从远处Git仓库读取。本地仓库是指将所有的配置文件统一写 在Config Server工程目录下Config Sever暴露Http API接口, ConfigClient通过调用Config Sever的Http API接口来读取配置文件。
构建Config Server
依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
启动类:
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
在工程的配置文件application.yml中做相关的配置,包括指定程序名为config-server,端口号为8769。通过spring. profiles.active=native来配置Config Server从本地读取配置,读取配置的路径为classpath下的shared目录。application.yml 配置文件的代码如下:
server:
port: 8769
spring:
application:
name: config-server
cloud:
config:
server:
native:
search-locations: classpath:/shared
profiles:
active: native
在工程的Resources目录下建一个shared文件夹,用于存放本地配置文件。在shared目录下,新建一个config-client-dev.yml
文件,用作eureka-client工程的dev (开发环境)的配置文件。在config-client-dev.yml配置文件中,指定程序的端口号为8762,并定义一个变量foo,该变量的值为foo version 1
。代码如下:
#作为eureka-client的dev配置
server:
port: 8762
foo: foo version 1
构建Config Client
新建一个工程,取名为config-client,该工程作为Config Client从Config Server读取配置文件,该工程的pom文件继承了主Maven工程的pom文件,并在其pom文件引入Config的起步依赖spring-cloud-starter-config和Web功能的起步依赖spring-boot-starter-web。代码如下:
<dependencies>
<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>
</dependencies>
在其配置文件bootstrap.yml
中做程序的配置,注意这里用的是bootstrap.yml, 而不是application.yml, bootstrap 相对于application 具有优先的执行顺序。在bootstrap.yml 配置文件中指定了程序名为config-client, 向Url地址为htp://ocalhost:8769 的Config Server 读取配置文件。如果没有读取成功,则执行快速失败( fail-fast),读取的是dev文件。
bootstrap.yml 配置文件中的变量{spring.application.name}和变量{spring.profiles.active},两者以“-”相连,构成了向Config Server读取的配置文件名
, 所以本案例在配置中心读取的配置文件名 为config-client-dev.yml文件。配置文件bootstrap.yml的代码如下:
spring:
application:
name: config-client
cloud:
config:
uri: http://localhost:8769
fail-fast: true
profiles:
active: dev
启动类:
@SpringBootApplication
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
}
eureka-server工程启动成功后,启动eureka-client 工程,你会在控制台的日志中发现eureka-client向Url地址为http://localhost:8769的Config Server 读取了配置文件。最终程序启动的端口为8762,这个端口是在eureka-server的Resouces/shared 目录中的eureka-client-dev.yml的配置文件中配置的,可见eureka-client成功地向eureka-server 读取了配置文件。
为了进一步验证,在eureka-clien工程写一个API接口,读取配置文件的foo变量,并通过API接口返回,代码如下:
@RestController
public class Controller {
@Value("${foo}")
String foo;
@RequestMapping("/foo")
public String hi() {
System.out.println(foo);
return foo;
}
}
访问http://localhost:8762/foo
,显示:
可见kureka-client工程成功地向eureka-server工程读取了配置文件中foo变量的值。
还没有评论,来说两句吧...