- spring-cloud-config server 端的配置
需要引入的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
需要添加的注解
@EnableConfigServer
@SpringBootApplication
@EnableConfigServer
public class ConfigServer_3001 {
public static void main(String[] args) {
SpringApplication.run(ConfigServer_5001.class, args);
}
}
需要的配置文件
server:
port: 3001 #本服务的端口号
spring:
application:
name: microservice-config-application #github上的配置名称 此处不待yml
cloud:
config:
server:
git:
uri: https://github.com/liyiruo/microservice-cloud-config.git #github上的地址
测试:http://localhost:3001/microservice-config-application-dev.yml
测试:http://localhost:3001/microservice-config-application-prod.yml
测试:http://localhost:3001/microservice-config-application-test.yml
均成功获取到响应的配置信息
- spring-cloud-config client 端的配置
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
-
启动类不需要添加注解
-
bootstrap.yml 的配置内容
spring:
cloud:
config:
name: microservice-config-application #文件名称 不带yml
label: master #分支
uri: http://localhost:3001 #config服务端地址
profile: prod #激活的配置项 (在这里遇到本文要说的问题)
- application.yml里的配置内容
server:
port: 8080
spring:
application:
name: conflg-client
- 客户端controller 里内容
package com.liyiruo.springcloud.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class ConfigController {
@Value("${spring.application.name}")
private String applicationName;
@Value("${server.port}")
private String port;
@RequestMapping("/config")
public String config() {
String content = "应用名称为:" + applicationName + ";端口号为:" + port;
log.info("content:{}", content);
return content;
}
}
- 远程仓库里文件
microservice-config-application.yml
内容 为:
spring:
profiles:
active: dev
---
server:
port: 4001
spring:
profiles: prod
application:
name: microservice-config-prod
---
server:
prot: 4002
spring:
profiles: dev
application:
name: microservice-config-dev
---
server:
prot: 4003
spring:
profiles: test
application:
name: microservice-config-test
测试
bootstrap.yml
里的profile 为prod 时, http://localhost:4001/config
打开成功
测试bootstrap.yml
里的profile 为dev 时, http://localhost:4002/config
打开失败
测试bootstrap.yml
里的profile 为test时, http://localhost:4003/config
打开失败
问题:为什么会有2个失败呢?
经过一个高手的点拨,问题已解决。他告诉我,远程仓库里文件microservice-config-application.yml
里端口号的英文是 port
而不是prot
。在此向高人致敬。