springcloud之Config初識篇—客戶端獲取配置文件

我們的每個有配置文件的服務都是config的客戶端。客戶端通過調用服務端獲取遠程倉庫的配置文件,它自身不會和遠程倉庫做交互。

1、maven依賴

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--config客戶端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

2、yml配置
PS:這裏使用bootstrap.yml因爲使用Config的原因項目需要在開始啓動加載的時候就獲得配置文件信息,bootstrap的加載優先級高於application所以使用Config的話需要將application.yml改爲bootstrap.yml否則啓動時會報錯。

spring:
  application:
    name: config-client
  cloud:
    config:
      #和下面的discovery互斥(不使用eureka 的話可以使用這種方式)
#      uri:
#        - http://localhost:8100
      discovery:
        enabled: true
        # configserver的服務id,我們通過sever獲取遠程倉庫的信息  
        service-id: config-server
      profile: dev
      label: master

server:
  port: 8011
eureka:
  instance:
    instance-id: config-client
    hostname: config-client
  client:
    service-url:
      defaultZone: http://eurekaServer:8700/eurekaServer/eureka
#自定義配置
name: "this is name"
time: 123

3、java配置類

@EnableEurekaClient
@SpringBootApplication
public class ConfigClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigClientApplication.class, args);
    }

}

4、編寫一個測試類

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by py
 */
@RefreshScope
@RestController
public class FirstController {
    @Value("${name}")
    private String name;
    @Value("${time}")
    private String time;

    @RequestMapping("/firstConfig")
    public String queryConfigInfo(){
        System.out.println("name:"+name);
        System.out.println("time:"+time);
        return name+"=="+time;
    }
}

5、啓動服務

6、請求服務(獲取到遠程配置文件的信息)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章