2017-05-12 1 views
1

런타임시 스프링 구성 서버에 일부 등록 정보를 추가하려고하고 @Value 주석이있는 모든 클라이언트 응용 프로그램에서 사용할 수 있어야합니다.런타임시 스프링 구성 서버 등록 정보 추가

스프링 설정 서버에서 값을 계산하고 환경에 추가하기 때문에이 속성을 미리 정의하지 않아도됩니다.

이 문제를 해결하는 가장 좋은 방법이 무엇인지 이해시켜 주시겠습니까?

+0

이 답변을 살펴보십시오. [Spring Cloud Config Server + RabbitMQ]의 복제본 (http : // stackoverflow)이 가능한 답변은 http://stackoverflow.com/questions/37873433/spring-cloud-config-server-rabbitmq/37873783#37873783 –

+0

입니다. .com/questions/37873433/spring-cloud-config-server-rabbitmq) – Raz0rwire

+1

다른 질문이 없습니다. –

답변

2

스프링 클라우드 구성에는 실행중인 응용 프로그램의 등록 정보와 빈을 새로 고칠 수있는 'RefreshScope'이라는 기능이 있습니다.

스프링 클라우드 설정에 대해 읽는다면 git 저장소의 속성 만로드 할 수있는 것처럼 보이지만 사실이 아닙니다.

RefreshScope를 사용하면 외부 git 저장소 또는 HTTP 요청에 연결할 필요없이 로컬 파일에서 속성을 다시로드 할 수 있습니다.

이 내용을 가진 파일 bootstrap.properties을 만듭니다

# false: spring cloud config will not try to connect to a git repository 
spring.cloud.config.enabled=false 
# let the location point to the file with the reloadable properties 
reloadable-properties.location=file:/config/defaults/reloadable.properties 

은 위에서 정의 된 위치에 파일 reloadable.properties을 만듭니다. 비워 두거나 속성을 추가 할 수 있습니다. 이 파일에서 나중에 런타임에 속성을 변경하거나 추가 할 수 있습니다.

은 런타임시 변경 될 수 있습니다 속성을 사용하는

<dependency> 
    <groupId>org.springframework.cloud</groupId> 
    <artifactId>spring-cloud-starter-config</artifactId> 
</dependency> 

모든 콩에 종속성을 추가, 같은 @RefreshScope 주석해야합니다

@Bean 
@RefreshScope 
Controller controller() { 
    return new Controller(); 
} 

클래스를 생성

public class ReloadablePropertySourceLocator implements PropertySourceLocator 
{ 
     private final String location; 

     public ReloadablePropertySourceLocator(
      @Value("${reloadable-properties.location}") String location) { 
      this.location = location; 
     } 

    /** 
    * must create a new instance of the property source on every call 
    */ 
    @Override 
    public PropertySource<?> locate(Environment environment) { 
     try { 
      return new ResourcePropertySource(location); 
     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 

해당 클래스를 사용하여 bootstrap the configuration으로 스프링 구성 .

리소스 폴더에 META-INF/spring.factories 파일을 만듭니다 (또는 확장) :

org.springframework.cloud.bootstrap.BootstrapConfiguration=your.package.ReloadablePropertySourceLocator 

이 콩은 reloadable.properties에서 속성을 읽습니다. Spring Cloud Config는 애플리케이션을 새로 고침 할 때 디스크에서 다시로드합니다.

런타임을 추가하고 reloadable.properties을 편집 한 다음 봄 컨텍스트를 새로 고칩니다. 당신은 /refresh 엔드 포인트에 POST 요청을 전송함으로써, 또는 ContextRefresher를 사용하여 자바 것을 수행 할 수 있습니다 원격 자식 저장소에서 속성에 병렬로 사용하도록 선택하는 경우

@Autowired 
ContextRefresher contextRefresher; 
... 
contextRefresher.refresh(); 

이것은 또한, 작동합니다.

+0

Stefan에게 감사드립니다.우리는 당신이 externalised 파일에 런타임 속성을 추가 할 수 있고 봄 설정 서버가 자동으로로드 할 것을 제안하는 것으로 알고 있습니다. 그러나 내가 파일을 작성하지 않고 성취 할 수있는 가능성이 있습니다. environment.addPorperty (key, Value)와 같은 방식으로 모든 설정 클라이언트에 사용할 수 있습니까? –

+0

@RefreshScope로 빈을 정의하는 대신 프로젝트에서 전역 적으로 처리 할 수 ​​있습니까? –

관련 문제