server端
1.pom中添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
2.啓動類
添加註解@EnableConfigServer
3.配置文件
application.yml配置文件
server:
port: 5000
spring:
application:
name: config-server
cloud:
config:
server:
git:
##定義去拉取本地配置的地址
uri: D:\\code\\item\\springcloud\\day02_config\\config-server\\src\\main\\resources\\configs
##遠程拉取配置文件的配置
##uri: https://github.com/936981178/springcloudconfig.git # 配置git倉庫的地址
##search-paths: config-repo # git倉庫地址下的相對地址,可以配置多個,用,分割。
##username: # git倉庫的賬號
##password: # git倉庫的密碼
management:
endpoints:
web:
exposure:
include: "*"
配置eurekaserver文件
一般都有三個環境的配置文件
```
spring:
application:
name: eureka-peer
server:
port: 10000
eureka:
instance:
hostname: dev
instance-id: dev
client:
fetch-registry: false
register-with-eureka: false
service-url:
defaultZone: http://localhost:10000/eureka/
server:
wait-time-in-ms-when-sync-empty: 0
enable-self-preservation: true
peer-eureka-nodes-update-interval-ms: 10000
4.git初始化
打開git初始化:
git init
git add .
git commit -m “frist commit”
啓動,訪問http://localhost:5000/eurekaserver/dev
可讀取到配置文件內容
eureka從配置中心拉取配置(config_client端)
1.pom依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
2.配置文件
config的相關配置是要先於application.properties的,所以需要使用bootstrap.yml,其配置文件的加載先於application.properties。
bootstrap,yml
server:
port: 10000
spring:
application:
##config服務configs的文件名對應
name: eurekaserver
cloud:
config:
name: eurekaserver
uri : http://localhost:5000/
profiles:
##config服務configs中對應文件名後面的環境
active: dev
啓動訪問http://localhost:10000/
測試
同eureka-server一樣,將上次的eureka-client交給config配置中心管理
配置文件
在config服務中新建helloclient-dev.yml配置文件
name: mcw
age : 22
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10000/eureka/
將配置文件添加到git中
git add helloclient-dev.yml
git commit -m "helloclient commit"
在eureka-client服務添加測試代碼
public class Teacher {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@RestController
public class HelloEurekaController {
@Value("${name}")
private String name;
@Value("${age}")
private int age;
@GetMapping("")
public Object index(){
Teacher teacher = new Teacher();
teacher.setAge(this.age);
teacher.setName(this.name);
return teacher;
}
}
啓動訪問http://localhost:8001/
示例代碼
碼雲