版本
springboot
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
springcloud
<spring-cloud.version>2020.0.1</spring-cloud.version>
配置中心config-server
引入依赖
<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>
启动类加注解
@EnableDiscoveryClient
@EnableConfigServer
@SpringBootApplication
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
配置文件application.yml
server:
port: 9005
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: http://git.xxx.com/xxx/config.git #gitlab地址
search-paths: /config-repo/*
username: your username #账号
password: your password #密码
label: master #分支名称
eureka:
client:
register-with-eureka: true
fetchRegistry: true
service-url:
defaultZone: http://localhost:7001/eureka
客户端config-client
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 要添加这个依赖,不然找不到值 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
启动类加注解
@EnableDiscoveryClient // 在注册中心发现服务
@SpringBootApplication
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
}
测试controller
@RestController
public class ConfigClientController {
@Value("${word}")
private String word;
@RequestMapping("/hello")
public String index(@RequestParam String name) {
return name+","+this.word;
}
}
bootstrap.yml
注意一定要是bootstrap 不然会读取不到
server:
port: 9006
spring:
application:
name: config-client
cloud:
#config客户端配置
config:
profile: dev #后缀名称
name: config-client #配置文件名称
label: master #分支名称
uri: http://localhost:9005/ #配置中心地址
eureka:
client:
register-with-eureka: true
fetchRegistry: true
service-url:
defaultZone: http://localhost:7001/eureka
将配置文件放到gitlab上
启动测试
1.依次启动eureka、config-server、config-client
2.访问地址http://localhost:9005/config-client-dev.yml
3.访问地址http://localhost:9006/hello?name=11
测试成功,搭建完成