Config Server
config server可以与eureka同体存在,但这里为了明确记录,就采用单独的module实现
在创建项目之前,需要在git上创建一个project,这里使用github
创建过程省略,这里给出project的结构
config-client文件夹内包含
yml文件内容是
这里将成为config-server的配置存储中心,此处仅有**(name = “hello”, value = “world”)**
下面开始创建项目
新建module
启动类
添加@EnableConfigServer注解
@SpringBootApplication
@EnableConfigServer //<- here
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
配置文件
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: https://github.com/CodeMd2z/config.git
search-paths: '{application}'
application:
name: config-server
uri的值为目标git地址,因为创建的project为公开的,所以这里不需要账号密码的配置,如果是私有,则需要:
spring:
cloud:
config:
server:
git:
uri: https://github.com/CodeMd2z/config.git
username: xxxxx
password: xxxxx
port为config-server监听的端口(如果不设置成8888,则会引发一些错误,后续记录)
此时即可启动config-server,在浏览器输入:http://localhost:8888/config-client/dev/master 即可看到
使用
然后在需要配置中心的配置的serivce项目配置文件中添加:
spring:
cloud:
config:
uri: http://localhost:8888/
profile: dev
label: master
即可调用配置中心的配置
uri 为config-server的地址
profile 为环境选择
label 为git的分支选择
刚刚说到,这里存在一个问题
我在最开始的时候把config-server启动在8765端口
但是当service调用配置中心的配置时仍然访问的是8888端口
查了资料之后才明白,服务必须获取了配置中心的配置之后才能启动,而获取的时候还没有读取application.yml的内容,因为它的优先级不高,但服务又需要一些配置才能启动,所以就优先读取bootstrap.yml以启动服务,然后才读取application.yml的内容
那么当问题解决,服务成功读取到配置中心的内容时,我们就可以看到它的效果了:
先在启动类添加一个示例接口:
在浏览器输入:http://localhost:8904/hello 即可得到git上那个文件里面的配置内容:(ps: 8904为服务启动的端口)