관리 메뉴

IT.FARMER

Spring Cloud Config 본문

Spring/Spring Boot

Spring Cloud Config

아이티.파머 2020. 6. 22. 15:27
반응형

Spring Cloud Config

스프링 클라우드, 그중에서 스프링 클라우드 컨피그는 MAS로 나뉘는 프로젝트의 공통 환경설정 값을들 공유하기 위해서 사용한다.

같은 설정파일을 여러번 고치거나 여러곳에 분산되어 설정을 적어주는 비용을 줄일수 있다.

 

Spring Cloud config 를 사용하기 위해서는 Cloud Config 의 두가지 성향을 기억하고 있어야 한다.

  • Spring Config Server : 공통 환경설정을 가지고 있는 Config Cloud Server
  • Spring Config Client : 공통 환경설정을 받아 사용하는 Application Server

1. Spring Config Server

먼저 Spring Config Server 에대서 알아보고 구현 해보자, 앞서 말한것 처럼 Spring Config Server는 공통 환경 설정을 가지고있는 서버로 다른 클라이언트에서 해당 서버로 붙어 공통 환경 설정을 읽어간다. 이때문에 해당 서버가 중지되어 있다면 문제가 생길수도 있는 문제점이 있다.

pom.xml

클라우드 서버요 라이브러리 의존설 설정

<properties>
    <java.version>1.11</java.version>
    <spring-cloud.version>Hoxton.SR5</spring-cloud.version>
</properties>

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

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

application.yml

참고하려는 cloud config application 파일 git 위치 , public 으로 열어 두고 다음처럼도 사용 가능 하며, SSH 인증 설정도 할 수 있다.

##########################################################################################
# 클라우드 컨피그레이션 참고
# https://cloud.spring.io/spring-cloud-config/multi/multi__spring_cloud_config_server.html
##########################################################################################

server:
  port: 8888

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/an-sangkil/msa-it-farm.git
          search-paths: configuration
          #password:
          #username:

management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    env:
      enabled: true
  • spring.cloud.config.server.git.seatch-paths : 깃 주소에서 위치를 지정해 가능한 옵션

cloud config application 파일

https://github.com/an-sangkil/msa-it-farm.git 경로에 있는 클라우드 컨피그 파일 을 생성한다. 기본적으로 application.yml 을 읽어 드리도록 되어 있다. 추후 spring-cloud-config-client 에서 이야기 하겠지만 ${application-name}-{profileactive}.yml 로 파일을 생성한다.

 

 

 

파일 예제 ( itfarmserver-dev.yml )

google:
  id: skan_dev
  password: skan!!!!

어플리케이션 실행

@EnableConfigServer 으로 컨피그 서버를 활성화하여 어플리케이션을 실행한다.

@SpringBootApplication
@EnableConfigServer
public class CloudConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(CloudConfigServerApplication.class);
    }
}

이로써 Spring Cloud Server 작업은 완료 되었으며,

curl -x http//127.0.0.1/itfarmserver/dev 를 실행하면, 방금전에 만들어 놓은 컨피그 정보를 확인 할 수 있다.

 

{
    "name": "itfarmserver",
    "profiles": [
        "dev"
    ],
    "label": null,
    "version": "2dc41b35dee60133900101067f970fbc0be101cf",
    "state": null,
    "propertySources": [
        {
            "name": "https://github.com/an-sangkil/msa-it-farm.git/configuration/itfarmserver-dev.yml",
            "source": {
                "google.id": "skan_dev",
                "google.password": "skan!!!!"
            }
        },
        {
            "name": "https://github.com/an-sangkil/msa-it-farm.git/configuration/application.yml",
            "source": {
                "google.id": "skan_application",
                "google.password": "skan!!!!"
            }
        }
    ]
}

2. Spring Cloud Config - Client

스프링클라우드 컨피그로 클라이언트에서 받아올수 환경은에제 갇추어 졌다. 이제 클라이언트에서 환경설정하여, 클라우드에서 컨피그를 받아 오도록 한다.

클라이언트에서 설정시 bootstrap.yml 에 설정 하도록 한다. bootstrap.yml 은 application.yml 을 읽어드리기 전에 최초로 먼저 읽어 드리는 환경 설정파일이다.

##########################################################################################
# 클라우드 컨피그레이션 참고
# https://cloud.spring.io/spring-cloud-config/reference/html/
##########################################################################################

spring:
  application:
    name: itfarmserver
  profiles:
    active: dev
---
spring:
  profiles: local
  cloud:
    config:
      enabled: false
      fail-fast: false  # config server 와 연결이 되어 있지 않으면 예외를 발생시키고 종료 시키려면  fail-fast를 TRUE로 설정한다.
---
spring:
  profiles: test
  cloud:
    config:
      uri: http://localhost:8888
      fail-fast: false
---
spring:
  profiles: dev
  cloud:
    config:
      uri: http://localhost:8888
      fail-fast: false
  • spring.application.name spring config server에서 읽어드릴 application 명으로 /configuration/${application}-{profiles}.yml 파일의 ${application} 명을 지정하고 맞춰 주도록 한다.
  • spring.cloud.config.fail-fast → config server와 연결이 되어 있지 않으면 서버가 시작시 예외를 발생시키고 종료 된다. (기본값은 false)
  • spring.cloud.config.enabled → 클라우드 설정 사용 여부로 기본 true 이다. false로 변경하여 특정 환경에서는 클라우드 컨피그를 사용하지 않을수도 있다.

Spring Application 확인

클라이언트 어플리 케이션을 실행시켜 google.id 의 값이 Spring cloud에서 잘받아와 지는지 확인

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

@Component
class WebClientStart implements CommandLineRunner {

    @Value("${google.id}")
    private String googleId;

    @Override
    public void run(String... args) throws Exception {
        System.out.println(String.format("googleId = %s", googleId));
    }
}

logging 확인

2020-06-22 15:13:27.415  INFO 37980 --- [  restartedMain] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-06-22 15:13:27.415  INFO 37980 --- [  restartedMain] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-06-22 15:13:27.430  INFO 37980 --- [  restartedMain] com.skan.farm.WebClientApplication       : Started WebClientApplication in 31.981 seconds (JVM running for 35.5)
googleId = skan_dev
2020-06-22 15:13:28.288  INFO 37980 --- [4)-10.184.70.55] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-06-22 15:13:28.289  INFO 37980 --- [4)-10.184.70.55] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-06-22 15:13:28.297  INFO 37980 --- [4)-10.184.70.55] o.s.web.servlet.DispatcherServlet        : Completed initialization in 7 ms
2020-06-22 15:13:28.298  INFO 37980 --- [3)-10.184.70.55] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...

 

Spring Cloud의 또하나의 장점으로는 환경설정 값을 실시간으로도 반영이 가능 하다는것이다.

@RefreshScope 를 설정하고 git 의 파일을 수정하면 실시간으로 반영되어 결과가 나온다.

 

@RestController
@RefreshScope
public class TestRestController {

    @Value("${google.id:some default value }")
    private String googleId;

    @GetMapping("/get")
    public String testCloudConfig() {
        return googleId;
    }
}
반응형

'Spring > Spring Boot' 카테고리의 다른 글

Spring boot admin  (0) 2020.06.22
Spring devtools restart 파일 감지  (0) 2018.08.31
Springboot jpa & Hibernate Naming Strategy(네이밍 전략)  (1) 2018.08.31
Spring boot Swagger  (0) 2017.08.31
Spring Boot mobile project 에 tiles 적용  (0) 2017.02.03