分布式配置中心服务端
pom.xml
添加 spring-cloud-config-server
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
Application
通过 @EnableConfigServer` 注解,开启配置服务功能
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;
@SpringBootApplication
@EnableConfigServer
@EnableEurekaClient
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
bootstrap.yml
增加 Config 相关配置,并设置端口号为:8888
spring:
application:
name: hello-spring-cloud-config
cloud:
config:
label: master
server:
git:
uri: https://github.com/***/spring-cloud-config
search-paths: respo
username:
password:
server:
port: 8888
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
相关配置说明,如下:
spring.cloud.config.label
: 配置仓库的分支spring.cloud.config.server.git.uri
:配置 Git 仓库地址spring.cloud.config.server.git.search-paths
: 配置仓库路径(存放配置文件的目录)spring.cloud.config.server.git.username
: 访问 Git 仓库的账号sping.cloud.config.server.git.password
:访问 Git 仓库的密码
HTTP 请求地址和资源映射文件
- http://ip:port/{application}/{profile}[/{label}]
- http://ip:port/{application}-{profile}.yml
- http://ip:port/{label}/{application}-{profile}.yml
- http://ip:port/{application}-{profile}.properties
- http://ip:port/{label}/{application}-{profile}.properties
分布式配置中心客户端
pom.xml
添加 sping-cloud-starter-config
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Application
入口类没有需要特殊处理的地方,代码如下:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
}
bootstrap.yml
增加 Config Client
相关配置,并设置端口号为:8889
spring:
application:
name: hello-spring-cloud-config-client
cloud:
config:
uri: http://localhost:8888
name: config-client
label: master
profile: dev
server:
port: 8889
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
相关配置说明,如下:
-
spring.cloud.config.uri
:配置服务中心的网址 -
spring.cloud.config.name
: 配置文件名称的前缀 -
spring.cloud.config.label
: 配置仓库的分支 -
spring.cloud.config.profile
: 配置文件的环境标识- dev:表示开发环境
- test:表示测试环境
- prod:表示生产环境
注意事项:
- 配置服务器的默认端口为
8888
,如果修改了默认端口,则客户端项目就不能在application.yml
或application.properties
中配置spring.cloud.config.uri
,必须在bootstrap.yml
或是bootstrap.properties
中配置,原因是bootstrap
开头的配置文件会被优先加载和配置。
开启 Spring Boot Profile
java -jar hello-spring-cloud-web-admin-feign-1.0.0-SNAPSHOT.jar --spring.profiles.active=prod