ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • spring cloud config (watcher) 구현하기 3
    카테고리 없음 2024. 8. 1. 13:06
    반응형

    서버를 껐다 켜지 않아도 데이타가 refresh 되는 spring cloud config!

    data를 refresh 하는 방법은 수동/자동 두 가지가 있다.

     

    수동 방법

    actuator/refresh 호출하고 rest api 호출하면 data refresh 가 된다.

    가장 기본적인 방법이지만 매번 api를 호출 해줘야 하기 때문에 귀찮은 방법.

     

    (위의 방법을 사용하려면 actuator dependency 등록을 해줘야된다.)

     

    자동 방법

    scheduler를 사용한다.(config client watcher)

     

    1. application.properties 에 configClientWatch 설정 추가

    spring.cloud.config.watch.enabled=true
    spring.cloud.config.watch.initialDelay=5000
    spring.cloud.config.watch.delay=10000

     

    2.scheduler 생성

    
    import java.io.Closeable;
    import java.util.concurrent.atomic.AtomicBoolean;
    
    import javax.annotation.PostConstruct;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.cloud.config.client.ConfigClientStateHolder;
    import org.springframework.cloud.context.refresh.ContextRefresher;
    import org.springframework.context.EnvironmentAware;
    import org.springframework.core.env.Environment;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Service;
    
    @Service
    public class ConfigClientWatchScheduler implements Closeable, EnvironmentAware {
    
    	private final AtomicBoolean running = new AtomicBoolean(false);
    
    	private final ContextRefresher refresher;
    
    	private Environment environment;
    
    	public ConfigClientWatchScheduler(ContextRefresher refresher) {
    		this.refresher = refresher;
    	}
    
    	@Override
    	public void setEnvironment(Environment environment) {
    		this.environment = environment;
    	}
    
    	@PostConstruct
    	public void start() {
    		this.running.compareAndSet(false, true);
    	}
    
    	private Logger logger = LoggerFactory.getLogger(ConfigClientWatchScheduler.class);
    	
    	
    	@Scheduled(initialDelayString = "${spring.cloud.config.watch.initialDelay}", fixedDelayString = "${spring.cloud.config.watch.delay}")
    	public void watchConfigServer() {
    		
    		if (this.running.get()) {
    		
    			this.refresher.refresh();
    		}
    	}
    
    	 
    	@Override
    	public void close() {
    		this.running.compareAndSet(true, false);
    	}
    
    }

     

     

    this.refresher.refresh()로 주기적으로 값을  refresh 하여 가져오게된다.

     

     

    참고 사이트

    https://github.com/spring-cloud/spring-cloud-config/blob/main/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientWatch.java

    반응형

    댓글

Designed by Tistory.