一、创建项目需添加的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
二、启动类加@EnableConfigServer注解
package demo.configserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@EnableConfigServer
@SpringBootApplication
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
三、配置文件
spring.application.name=config-server
server.port=8081
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
spring.cloud.config.server.git.uri=https://gitee.com/zhiziopen/news-spring-cloud-config-server.git
spring.cloud.config.server.git.username=zhiziopen
spring.cloud.config.server.git.password=
四、通过地址访问配置文件
URL和配置文件的映射关系
*/{application}/{profile}/{label}
如:
http://localhost:8081/news-user/dev/dev
http://localhost:8081/news-user/prod/master
*/{application}-{profile}.properties/yml
如:
http://localhost:8081/news-user-dev.properties
http://localhost:8081/news-user-prod.yml
*/{label}/{application}-{profile}.properties/yml
如:
http://localhost:8081/master/news-user-dev.properties
http://localhost:8081/dev/news-user-prod.yml
application:应用(文件名不包括环境后缀,如news-user)
profile:环境(文件名后缀,如dev,prod)
label:Git仓库分支名
合并规则
news-user-dev.properties
news-user-prod.properties
news-user.properties
我创建了上面三文件,其中news-user.properties(后面未加环境变量)为公共配置,访问news-user-dev.properties或news-user-prod.properties会自动将news-user.properties的内容合并到对应的文件中。