Spring Cloud (MSA)

Config Client 구축하기

hnev 2022. 9. 26. 16:09

▶ Spring Cloud Config Client

Config-Server를 Fetching 하여 환경 구성 데이터를 읽어오는 Config-Client를 설정해본다.

고유 목적의 마이크로 서비스는 동일한 Config-Server를 설정함으로써 공통적인 환경을 갖추거나 애플리케이션에 맞게 가져올 수 있다. 그리고 actuator의 refresh를 통해 변경된 설정 값도 서버의 재시작 없이 적용이 가능하다.

 

build.gradle

plugins {
	id 'org.springframework.boot' version '2.5.6'
	id 'io.spring.dependency-management' version '1.0.11.RELEASE'
	id 'java'
}

group = 'com.venh.msa'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

ext {
	set('springCloudVersion', "2020.0.4")
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-actuator'
	implementation 'org.springframework.cloud:spring-cloud-starter-config'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

dependencyManagement {
	imports {
		mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
	}
}

test {
	useJUnitPlatform()
}

 

application.yml

Config-Server의 http://localhost:8888를 import 하고
spring.application에 작성된 application-name-profile-active.yml
(즉, venh-dev.yml을 읽어온다.)

*Config-Server는 실행 중이어야 한다.

actuator 사용을 위한 설정을 해준다. 
여러 기능이 있지만 여기서는 config를 재요청하는 refresh만 설정한다.
server: 
  port: 8080
spring: 
  application:
    name: venh
  profiles:
    active: dev
  config: 
    import: optional:configserver:http://localhost:8888
    
#actuator config
management:
  endpoints:
    web:
      exposure:
        include: refresh

 

컨트롤러(Controller)

venh-dev.yml의 venh.test 값을 @Value 어노테이션을 통해 가져온다.

@RefreshScope는 설정이 변경될 경우 해당 어노테이션이 설정된 Bean에 대해 Config-Server의 변경정보를 참조하여 Bean을 다시 리로드 할 수 있게 해 준다.
@RestController
@RefreshScope
public class ConfigController {
	@Value("${venh.test}") 
	private String str; 
	
	@GetMapping("/test") 
	public String test() { 
		return str; 
	}
}

 

테스트 (Postman 사용) - 포스트맨(Postman) 설치 및 사용법

1) Config-Server 실행
2) Config-Client 실행

콘솔 로그를 살펴보면 Config Server가 Fetching 된 걸 확인할 수 있다.

 

 

http://localhost:8080/test를 호출한다.
venh.test 데이터가 정상적으로 출력되는지 확인한다.

 

 

git에서 venh.test 값을 변경한 뒤, 서버를 재시작하지 않고 POST 요청으로
http://localhost:8080/actuator/refresh를 요청하면 Bean를 리로드 한다.

 

 

http://localhost:8080/test를 호출한다.
변경된 venh.test 값을 확인한다.

 

GitHub