BackEnd/Spring Cloud
Spring Cloud Config
hanseom
2022. 7. 2. 10:20
반응형
Spring Cloud Config
- 분산 시스템에서 서버, 클라이언트 구성에 필요한 설정 정보(application.yml)를 외부 시스템에서 관리
- 하나의 중앙화 된 저장소에서 구성요소 관리 가능
- 각 서비스를 다시 빌드하지 않고, 바로 적용 가능
- 애플리케이션 배포 파이프라인을 통해 DEV-STAGE-PROD 환경에 맞는 구성 정보 사용
yml 파일 생성
hello.yml 파일을 생성하고 git에 commit합니다.
- 생성 위치: /Users/hansekim/Desktop/Work/git-local-repo
- yml 파일 우선순위: application.yml > application-name.yml > application-name-<profile>.yml
# hello.yml
greeting:
message: hello, config server!
# git 반영 명령어
git init
git add .
git commit -m "initial"
Spring Cloud Config 프로젝트 생성
@EnableConfigServer
package com.example.configservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServiceApplication.class, args);
}
}
application.yml
server:
port: 8888
spring:
application:
name: config-service
cloud:
config:
server:
git:
uri: file:///Users/hansekim/Desktop/Work/git-local-repo
http://localhost:8888/hello/default 접속
default는 profile로 hello-dev.yml 파일 존재 시 http://localhost:8888/hello/dev로 호출하면 됩니다. 기본 값은 default 입니다.
profile 확인을 위해 동일 경로에 hello-dev.yml 파일 생성 후 서버를 재기동하고 http://localhost:8888/hello/dev 호출합니다.
greeting:
message: hello dev, config service.
Users Microservice - Spring Cloud Config 연동
의존성 추가
dependencies {
... 생략 ...
implementation 'org.springframework.cloud:spring-cloud-starter-config'
implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap'
... 생략 ...
}
bootstrap.yml
Spring Cloud Config 서버 설정을 위해 bootstrap.yml 파일을 추가합니다. bootstrap.yml 파일은 application.yml 파일보다 우선순위가 높습니다.
spring:
cloud:
config:
uri: http://127.0.0.1:8888
name: hello
UserController.java
설정 정보를 잘 가지고 오는지 Controller에 Environment를 추가하여 확인합니다.
package com.example.userservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/")
public class UserController {
private final Environment env;
@Autowired
public UserController(Environment env) {
this.env = env;
}
@GetMapping("/welcome")
public String welcome() {
String configMessage = env.getProperty("greeting.message");
return "Hello, User-service: " + configMessage;
}
}
Spring Cloud Bus
변경된 설정 정보를 반영하기 위해서는 아래와 같은 방법이 존재합니다.
- 서버 재기동
- Actuator refresh: Spring Boot Actuator를 사용하여 refresh 합니다.
- Spring Cloud Bus: 분산 시스템의 노드를 경량 메시지 브로커와 연결하여 상태 및 구성에 대한 변경 사항을 연결된 노드에게 전달합니다.(Broadcast)
메시지 브로커인 RabbitMQ를 사용한 Spring Cloud Bus 구현 방법
[참고 정보]
반응형