서비스를 운영하다보면 서버의 설정 값들을 동적으로 바꾸고 싶은 니즈가 생긴다. 이럴때 Zookeeper를 이용하면 손쉽게 동적으로 변경 가능한 설정값을 사용할 수 있다.
Spring과 Zookeeper 연동
Spring과 Zookeeper를 연동하면, Spring Environment를 이용해 Zookeeper Node에 있는 데이터를 읽어올 수 있다. 여기서 장점은 데이터를 로컬에 저장해두기 때문에 빠르게 원하는 데이터를 가져올 수 있다는 점이다.
연동 가이드는 아래 문서를 참고하면 쉽게 연동할 수 있다.
https://docs.spring.io/spring-cloud-zookeeper/reference/config.html
Distributed Configuration with Zookeeper :: Spring Cloud Zookeeper
Zookeeper provides a hierarchical namespace that lets clients store arbitrary data, such as configuration data. Spring Cloud Zookeeper Config is an alternative to the Config Server and Client. Configuration is loaded into the Spring Environment during the
docs.spring.io
UnderTheHood
좀 더 나아가 연동하면, 어느시점에 Zookeeper에 있는 값을 가져오고, Zookeper 데이터가 변경되면 어떻게 값들이 최신화되는지 코드를 알아보자.
Initinalized
Zookeper 값이 처음 저장되는 시점은 Spring Environment 객체가 만들어지는 시점이다. 자세한 Flow는 아래와 같다.

- SpringApplication에서 SpringEventPreparedEvent를 발행
- 1번 이벤트에 의해 ConfigDataEnvironmentPostProcessor 실행
- ConfigDataEnvironmentPostProcessor에서 ConfigDataImporter를 이용해 ConfigData를 가져오고, ConfigDataImporter는 ZookeeperConfigDataLoader객체를 통해 Zookeeper에 있는 데이터를 가져온다.
아래는 ZookeeperConfigDataLoader의 load 메서드의 일부이다. 코드를 보면 Curator(Zookeeper Cient)를 이용해 해당 값을 ZookeeperPropertySource에 넣어서 만들어주는걸 확인할 수 있다.
@Override
public ConfigData load(ConfigDataLoaderContext context, ZookeeperConfigDataResource resource) {
try {
CuratorFramework curator = context.getBootstrapContext().get(CuratorFramework.class);
if (curator == null) {
// this can happen if certain conditions are met
return null;
}
ZookeeperPropertySource propertySource = new ZookeeperPropertySource(resource.getContext(),
curator);
List<ZookeeperPropertySource> propertySources = Collections.singletonList(propertySource);
if (ALL_OPTIONS.size() == 1) {
...
Zookeeper Node Update
코드를 살펴보면 Zookeeper 데이터는 TreeCache 객체에 저장된다. 그리고 TreeCache 객체는 Zookeeper를 계속 추적하면서 데이터 변경이 생기면 ConfigWater에서 RefreshEvent를 발송한다. 그러면 Spring에서 이벤트를 받아 Environment를 최신 값으로 업데이트해준다.
Get Zookeeper Data
연동을 했다면, Spring Environment를 통해 Zookeeper에 있는 데이터를 읽을 수 있다.
env.getProperty("key")
이때 데이터는 ZookeeperPropertySource에서 가져온다. 즉, 메모리에 올라가있는 데이터를 가져오기때문에 속도는 걱정하지 않아도된다.
'Spring' 카테고리의 다른 글
Feign Client 사용법 익히기 (0) | 2025.03.30 |
---|---|
WebClient를 이용한 외부 호출 관련 Metric 수집 (0) | 2025.03.02 |
Application Context Refresh 전에 로깅 설정하기 (1) | 2025.02.17 |
Spring Event UnderTheHood (0) | 2025.02.04 |
Spring @Transactional 동작원리 완벽 정리 (0) | 2024.03.02 |