Backend/MSA

241125 컨피그 서버 (Spring Cloud Config) 실습 TIL

drinkgalaxy 2024. 11. 26. 12:19

Spring Cloud Config 란?

분산 시스템 환경에서 중앙 집중식 구성 관리를 제공하는 프레임워크이다.

 

- 중앙 집중식 구성관리 : 분산 시스템에서 각 마이크로서비스의 설정을 중앙 Config 서버에서 관리하도록 해주는 도구이다. 

이를 통해 마이크로 서비스가 각각 독립적으로 설정 파일을 관리하지 않아도 되므로 유지보수가 간편해진다.

 

- 환경별 구성 : Config 서버는 개발, 테스트, 운영 등 환경별로 구성을 분리하여 관리할 수 있다.

 

- 실시간 구성 변경 : 설정 변경 시 애플리케이션을 재시작하지 않고도 실시간으로 반영할 수 있다.

실시간 구성 변경 방법에는 여러가지가 있다.

1) 수동으로 /actuator/refresh 엔드포인트 사용하기

2) Spring Cloud Bus 사용하기

 

컨피그 서버 생성 후 포트 정보 및 메시지 컨피그 서버에서 가져오기 실습하기

 

Config-server 구성하기

@SpringBootApplication
@EnableConfigServer
public class ConfigApplication {

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

 

 

config-server의 resources 안에 config-repo라는 폴더를 생성한 후 아래의 두 파일을 만든다.

 

- product-service.yml

server: 
  port: 19093 
    message: "product-service message"

 

- product-service-local.yml

server: 
  port: 19083 
    message: "product-service-local message"

 

 

 

Product 애플리케이션 수정하기

 

그리고 product-server의 resources 안에 있는 application.yml 에는 port를 임시로 0으로 설정해주고, message를 "default message" 라고 설정해주었다.

 

- ProductController

@RefreshScope 어노테이션은 Spring 애플리케이션의 빈이 설정 변경을 반영할 수 있도록 하는 역할을 한다.

이 어노테이션을 사용하면 /actuator/refresh 엔드포인트를 호출하여 설정 변경 사항을 동적으로 반영할 수 있다. 

@RefreshScope
@RestController
@RequestMapping("/product")
public class ProductController {

    @Value("${server.port}") // 애플리케이션이 실행 중인 포트를 주입받습니다.
    private String serverPort;

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

    @GetMapping
    public String getProduct() {
        return "Product detail from PORT : " + serverPort + " and message : " + this.message ;
    }
}

 

그럼 이제 직접 서버, 컨피크 서버, 상품을 실행해서 테스트해보자.

 

테스트 진행 

 

product-server의 application.yml에 설정해둔 포트가 0 임에도 config-server 에 설정한 19083 포트로 뜬다. 

메시지도 product-server application.yml에 설정해둔 "default message" 가 아닌, config-server에 설정해둔 "product-service-local message"가 뜬다.

그럼 이제 config-server의 product-service-local.yml 파일의 message를 수정하고 config-server만 재시작 해보자. 과연 메시지 업데이트가 잘 될까?

server: 
  port: 19083 
    message: "product-service-local message update"


일단 메시지 변경 후 /actuator/refresh 로 post 요청을 보내 수동으로 어플리케이션을 refresh한다.

 

다시 product를 확인해보면 메시지 변경이 잘 된 것을 볼 수 있다.

 

이렇게 config-server에서 원하는 애플리케이션의 환경 설정 파일을 관리하고, 애플리케이션의 재시작 없이 설정을 변경할 수 있다.