ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring Boot] Spring Cloud Config 연동하기
    Spring Boot/기타 2024. 3. 7. 23:35
    반응형

    Spring Cloud Config란?

    Spring Cloud Config는 애플리케이션의 설정 정보를 외부 저장소(GitHub Repository, File System 등)에서 가져와서 한 곳에서 관리하는 데 도움을 주는 라이브러리입니다.

    장점

    • 애플리케이션의 모든 설정을 한 곳에서 관리할 수 있으며, 이를 통해 일관성을 유지하고 관리 용이성을 향상할 수 있습니다.
    • 설정값을 변경하고, 이러한 변경 사항은 애플리케이션의 재배포 없이 실시간으로 적용할 수 있습니다.

    단점

    • 외부 저장소(GitHub Repository, File System 등)에서 설정 정보를 가져오는데, 이러한 저장소에 장애가 발생하면 해당 설정 정보를 참조하는 시스템에 장애가 전파될 수 있습니다.
    • 설정 파일의 우선순위 따라 의도치 않은 설정값이 적용될 수 있습니다. 


    설정 파일의 우선순위

    1. 프로젝트의 application.yaml 또는 application.properties 
      • 이들 설정은 모든 애플리케이션과 프로필에 적용되며, 기본 설정값을 제공합니다. 이들은 모든 애플리케이션과 프로필에 대한 공통의 기본값을 설정하는 데 사용됩니다.
    2. 설정 저장소의 application.yaml 또는 application.properties
      • 이들 설정은 모든 애플리케이션과 프로필에 적용되며, 프로젝트의 application.yaml 또는 application.properties에 정의된 설정을 오버라이드합니다.
    3. 프로젝트의 application-{profile}.yaml 또는 application-{profile}.properties 
      • 이들 설정은 특정 프로필에만 적용되며, application.yaml 또는 application.properties에 정의된 설정을 오버라이드합니다.
    4. 설정 저장소의 {application}/{application}-{profile}.yaml 또는 {application}/{application}-{profile}.properties 
      • 이들 설정은 특정 애플리케이션의 특정 프로필에만 적용되며, 이전 설정을 오버라이드합니다.

    참고: https://docs.spring.io/spring-cloud-config/docs/current/reference/html/
    참고 : https://www.baeldung.com/spring-cloud-configuration

     

    GitHub Repository 설정

    설정 파일을 저장하기 위한 GitHub Reository를 생성한 후 설정 파일을 업로드하세요. 

    GitHub Resository


    config-local.yml

    # LOCAL 환경 DataSource 설정
    spring:
      datasource:
        url: jdbc:h2:mem:local
        driver-class-name: org.h2.Driver.local
        username: username_local
        password: password_local


    config-dev.yml

    # DEV 환경 DataSource 설정
    spring:
      datasource:
        url: jdbc:h2:mem:dev
        driver-class-name: org.h2.Driver.dev
        username: username_dev
        password: password_dev


    Spring Cloud Config Server 설정

    1. 의존성 추가
    spring-boot-starter-web, spring-boot-starter-actuator, spring-cloud-config-server 의존성을 추가하세요.

    • spring-boot-starter-actuator : 애플리케이션의 상태 모니터링 기능을 제공
    • spring-cloud-config-server : 분산 시스템의 중앙화된 외부 설정 관리를 지원


    build.gradle

    dependencies {
    
        // Spring Boot
        implementation 'org.springframework.boot:spring-boot-starter-web'
        implementation 'org.springframework.boot:spring-boot-starter-actuator'
    
        // Spring Cloud
        implementation 'org.springframework.cloud:spring-cloud-config-server'
    }


    2. 환경 설정
    application.yml

    # server 설정
    server:
      port: 9091
    
    # config 설정
    spring:
      cloud:
        config:
          server:
            git:
              # GitHub 저장소의 주소
              uri: https://github.com/tychejin1218/spring-cloud-config-properties
              # GitHub 저장소의 브랜치
              default-label: main


    3. Spring Cloud Config Server를 설정하는 코드를 추가
    Spring Boot 애플리케이션을 Spring Cloud Config Server로 설정하기 위해, @EnableConfigServer 어노테이션 추가하세요.
    SpringCloudConfigServerApplication.java

    package com.example.springcloudconfigserver;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.config.server.EnableConfigServer;
    
    @EnableConfigServer
    @SpringBootApplication
    public class SpringCloudConfigServerApplication {
    
      public static void main(String[] args) {
        SpringApplication.run(SpringCloudConfigServerApplication.class, args);
      }
    }


    4. 설정 파일이 정상적으로 가져오는지 확인
    Spring Cloud Config Server에서 제공하는 EndPoint

    /{application}/{profile}[/{label}]
    /{application}-{profile}.yml
    /{label}/{application}-{profile}.yml
    /{application}-{profile}.properties
    /{label}/{application}-{profile}.properties
    • {application}은 클라이언트 애플리케이션의 spring.application.name 속성으로 정의되며, 클라이언트 애플리케이션의 이름을 의미합니다.
    • {profile}은 클라이언트 애플리케이션의 spring.profiles.active 속성으로 정의되며, 현재 활성화된 환경 프로필(예: local, dev, qa, prod 등)을 의미합니다.
    • {label}은 optional 값이며, Git의 branch를 의미합니다.


    4_1. localhost:9091/config/local 또는 localhost:9091/config/local/main


    4_2. localhost:9091/config-local.yml 또는 localhost:9091/main/config-local.yml


    4_3. localhost:9091/config-local.properties 또는 localhost:9091/main/config-local.properties


    Spring Cloud Config Client 설정

    1. 의존성 추가
    spring-boot-starter-web, spring-boot-starter-actuator, spring-cloud-starter-config 의존성을 추가하세요.

    • spring-cloud-starter-config : Spring Cloud Config 서버에서 애플리케이션 설정을 가져오는 기능을 제공


    build.gradle

    dependencies {
    
        // Spring Boot
        implementation 'org.springframework.boot:spring-boot-starter-web'
        implementation 'org.springframework.boot:spring-boot-starter-actuator'
    
        // Spring Cloud
        implementation 'org.springframework.cloud:spring-cloud-starter-config'
    }


    2. 환경 설정
    application.yml

    # Server 설정
    server:
      port: 9092
    
    # Config 설정
    spring:
      application:
        # Config Server에서 참조하는 설정 파일의 애플리케이션 이름을 설정
        name: config
      config:
        # 외부 설정 파일 설정 - Config Server 정보를 설정
        import: "optional:configserver:http://localhost:9091/"
      cloud:
        config:
          # 활성화할 프로파일을 설정(local, dev, qa, prod)
          profile: local


    3. Spring Cloud Config Server에서 설정 정보를 가져오는 코드를 추가
    @Value 어노테이션을 사용하여, 설정 파일의 속성을 필드에 주입하세요.
    ConfigController.java

    package com.example.springcloudconfigclient.controller;
    
    import com.example.springcloudconfigclient.service.ConfigService;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class ConfigController {
    
      private final ConfigService configService;
    
      public ConfigController(ConfigService configService) {
        this.configService = configService;
      }
    
      @GetMapping("/config")
      public ResponseEntity<?> getConfig() {
        return ResponseEntity.ok(configService.getConfig());
      }
    }


    ConfigService.java

    package com.example.springcloudconfigclient.service;
    
    import java.util.Map;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    
    @Service
    public class ConfigService {
    
      @Value("${spring.datasource.url}")
      private String url;
    
      @Value("${spring.datasource.driver-class-name}")
      private String driverClassName;
    
      @Value("${spring.datasource.username}")
      private String username;
    
      @Value("${spring.datasource.password}")
      private String password;
    
      public Map<String, String> getConfig() {
        return Map.of(
            "url", url,
            "driverClassName", driverClassName,
            "username", username,
            "password", password
        );
      }
    }



    4. 설정 정보를 정상적으로 가져오는지 확인
    4_1. localhost:9092/config

     


    소스 코드는 Github Repository 참조하세요.
    https://github.com/tychejin1218/spring-cloud-config-properties
    https://github.com/tychejin1218/spring-cloud-config

    반응형

    댓글

Designed by Tistory.