Spring Cloud Config -- server与client配置实践

参考文章:

Spring Cloud Config 使用本地配置文件

spring cloud config 统一配置中心 读取本地文件配置

 

一. Spring Cloud Config Server项目

1.pom.xml文件依赖

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-config-server</artifactId>
</dependency>

2.Application类中添加@EnableConfigServer注解

package com.sunbufu;

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);
    }
}

3 修改配置文件application.yml,指定本地客户端配置文件的路径

spring:
  profiles:
    active: native
  cloud:
    config:
      server:
        native:
          searchLocations: F:/conf

或者

Spring Cloud Config -- server与client配置实践

 4 准备客户端配置文件

Spring Cloud Config -- server与client配置实践

service-gateway-dev.yml文件内容:

server:
  #设置成0,表示任意未被占用的端口
  port: 8081
nickName: world

二.Spring Cloud Config Client项目

1 pom.xml中导入Config Client需要的包

(注意,此处跟Config Server的配置不同)

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

2 在src/main/resources中,新建bootstrap.yml文件 

bootstrap文件会在application文件之前加载,一般是不会变的。

spring:
  application:
    name: client
  cloud:
    config:
      uri: http://localhost:8080/
      name: service-gateway   #文件前缀名称
      profile: dev            # 服务环境名称  例如 {name}-{profile} = service-gateway-dev.yml,

可以使用Config Server的端点获取配置文件的内容。资源文件映射如下:

  • /{application}/{profile}[/{label}]
  • /{application}-{profile}.yml
  • /{label}/{application}-{profile}.yml
  • /{application}-{profile}.properties
  • /{label}/{application}-{profile}.properties

3 新建HelloController用来显示读取到的配置

package com.sunbufu.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Value("${nickName}")
    private String nickName;

    @RequestMapping("/hello")
    public String hello() {
        return "hello " + nickName;
    }
}

 

Spring Cloud Config -- server与client配置实践