응용 프로그램의 구성 소스는 일반적으로 원격 구성 서버 서버입니다. 기본적으로 로컬 구성 우선 순위는 원격 구성 저장소보다 낮습니다. 원격 저장소에서 속성 값을 덮어 쓰도록 로컬 애플리케이션 시스템 변수 및 구성 파일을 구현하려면 다음과 같이 설정할 수 있습니다.
스프링 : 클라우드 : config : allowoverride : trueoverridenone : trueoverrideystemproperties : false
위의 구성을 통해 클라이언트는 로컬 구성에서 더 높은 우선 순위를 달성 할 수 있으며 덮어 쓸 수 없습니다. 우리가 기반으로하는 Spring Cloud 의 현재 버전은 Edgware.RELEASE 이므로 위의 설정은 작동하지 않지만 PropertySourceBootstrapProperties 에서 기본값을 사용하십시오. 특정 상황은 https://github.com/spring-cloud/spring-cloud-commons/pull/250을 참조하십시오. 다음 분석에서 버그의 특정 소스에 대해 이야기하겠습니다.
소스 코드 분석
configservicePropertySourcelocator
원격 구성 속성을 덮어 쓰는 것은 궁극적으로 클라이언트 시작시 구성을 얻는 것과 관련이 있습니다. 구성을 얻은 후에 처리하는 방법은 무엇입니까? 스프링 클라우드 구성에서 리소스 획득 클래스 configservicepropertysourcelocator 의 클래스 다이어그램을 살펴 보겠습니다.
configservicePropertySourcelocator는 본질적으로 속성 자원 로케이터이며 주요 방법은 위치 (환경 환경)입니다. 먼저, ConfigclientProperties의 자리 표시자를 응용 프로그램이 현재 실행중인 환경의 애플리케이션, 프로필 및 레이블로 교체 한 다음 RESTTemplate을 초기화 한 다음 유효한 구성 정보가 얻어 질 때까지 레이블 배열을 통해 반복하고 최종적으로 빠르게 실패할지 여부에 따라 재 시도하십시오. 주요 과정은 다음과 같습니다.
위치 (환경 환경) HTTP를 통해 원격 서버에서 구성 데이터를 얻으려면 getRemoteenvironment (RestTemplate, Properties, Label, State) 메소드를 호출하십시오. 구현도 매우 간단합니다. 교체 요청의 경로에 자리 표시자를 표시 한 다음 헤더를 조립하십시오. 일단 조립되면 요청을 보내면 결과가 반환됩니다.
위의 구현에서 얻은 구성 정보가 CompositePropertySource에 저장되어 있음을 알 수 있습니다. 우리는 그것을 어떻게 사용합니까? 여기에 추가해야 할 또 다른 중요한 클래스는 ApplicationContextInitializer 인터페이스를 구현하는 PropertySourceBootStrapConfiguration입니다. 이 인터페이스는 응용 프로그램 컨텍스트가 새로 고침되기 전에 ()을 다시 호출하여 초기화 작업을 수행합니다. 응용 프로그램이 시작된 후 통화 스택은 다음과 같습니다.
SpringApplicationBuilder.run () -> SpringApplication.run () -> springApplication.createAndRefreshContext () -> springApplication.applyInitializers () -> PropertySourceBootStrapConfiguration.initialize () PropertySourcebootStrapConfiguration
위의 ConfigServicePropertySourcelocator의 위치 방법은 초기화로 호출되어 컨텍스트가 새로 고침되기 전에 필요한 구성 정보를 얻을 수 있도록합니다. 초기화 방법을 살펴 보겠습니다.
public class superysourcebootstrapconfigurationimplements applicationcontextinitializer <configurableApplicationContext>, orderded {private int order = orderded.highest_precedence + 10; @autowired (필수 = false) 개인 목록 <PropertySourcelOcator> PropertySourcelocators = new ArrayList <> (); @override public void initialize (configurableApplicationContext ApplicationContext) {compositePropertySource composite = new CompositePropertySource (bootstrap_property_source_name); // PropertySourcelOcators 배열을 정렬하고 기본 AnnotationAwareRorderComparator AnnotationAwareOrderComparator.sort (this.propertysourcelocators); 부울 빈 = 참; // 실행중인 환경 컨텍스트 컨텍스트 구성 구성 가능성 환경 = ApplicationContext.getenVironment (); for (propertySourcelocator locator : this.propertysourcelocators) {// transtraight this.propertysourcelocators propertysource <?> source = null; source = locator.locate (환경); if (source == null) {계속; } logger.info ( "위치 속성 출처 :" + 소스); // 링크 된 PropertySource Composite.AddPropertySource (source)에 소스를 추가합니다. 빈 = 거짓; } // 소스가 비어 있지 않은 경우에만 (! 빈) {// addfirst 및 addlast mutablePropertySources 속성 소송 = 환경과 같이 수행 할 수있는 가변 환경 형태를 반환하면 환경으로 설정됩니다. 문자열 logconfig = 환경. resolveplypplaceholders ( "$ {logging.config :}"); logfile logfile = logfile.get (환경); if (propertySources.contains (bootstrap_property_source_name)) {// bootstrapporties propertionsources.remove (bootstrap_property_source_name); } // 속성 소송 설정 insertPropertySources (PropertySources, Composite); reinitializeloggingsystem (환경, 로그 콘피드, 로그 파일); setLoglevels (환경); // 여러 actives를 처리하는 프로파일의 구성 정보 handleIncludedProfiles (환경); }} // ...}초기화 메소드에서 수행되는 작업이 수행되는 작업을 살펴 보겠습니다.
AddFirst, Addlast와 같이 수행 할 수있는 가변 형태의 환경을 반환합니다.
속성 소송에서 부트 스트로피트를 제거하십시오
Config Server 재정의 규칙에 따라 SET PropertySources
여러 활성 프로파일의 구성 정보를 처리합니다
초기화 메소드를 초기화 할 때 먼저 모든 PropertySourcelocator 유형 객체의 위치를 가로지 못한 다음 다양한 방식으로 CompositePropertySource 에 넣고 insertPropertySources (PropertySources, Composite) 메소드를 호출하여 환경으로 설정하십시오. Spring Cloud Context는 원격 속성을 덮어 쓰는 PropertySourceBootStrapperties를 제공 하고이 구성 클래스를 사용하여 속성 소스의 우선 순위를 결정합니다.
개인 void insertPropertySources (MutablePropertySources PropertySources, CompositePropertySource 복합재) {MutablePropertySources Incoming = New MutablePropertySources (); incoming.addfirst (composite); PropertySourceBootStroptroPerties RemoteProperties = new PropertySourceBootStrapperties (); New RelationDatabinder (RemoteProperties, "spring.cloud.config") .Bind (New PropertySourcesPropertyValues (Incoming)); // 로컬 덮어 쓰기가 허용되지 않는 경우 (! remoteproperties.isallowoverride () || (! remoteproperties.isoverridenone () && remoteproperties.isoverridesystemproperties ())) {propertySources.addfirst (composite); 반품; } // retormedenone은 사실입니다. 외부 구성은 if (remoteproperties.isoverridenone ()) {propertysources.addlast (composite); 반품; } if (propertySources .contains (StandardEnvironment.system_environment_property_source_name)) {// remoteproperties.isoverRidesyStemProperTies (! remotepRidesyStemProperTies (!))에 따라 외부 구성의 우선 순위를 설정합니다. StandardEnvironment.system_environment_property_source_name, composite); } else {propertySources.AddBefore (StandardEnvironment.system_environment_property_source_name, composite); }} else {propertySources.AddLast (composite); }}위의 구현은 주로 PropertySourceBootStroperties 의 속성을 기반으로 여러 구성 소스의 우선 순위를 조정합니다. 구현에서 기본 속성 값을 사용하여 PropertySourceBootStroperties 객체가 직접 초기화되고 구성 파일에서 설정 한 내용에 주입되지 않음을 알 수 있습니다.
수리 된 구현 :
@autowired (필수 = false) 사유지 소스 보트 부트 스트로페리티 remotepropertiesforoverriding; @override public int getorder () {return this.order; 개인 void insertPropertySources (MutablePropertySources PropertySources, CompositePropertySource 복합재) {MutablePropertySources Incoming = New MutablePropertySources (); incoming.addfirst (composite); PropertySourceBootStroperties RemoteProperties = remotepropertiesforOverRoverRiding == null? 새로운 PropertySourceBootStroperties () : remotepropertiesforeverriding;요약
위는 편집기가 소개 한 원격 구성 속성 예제를 우선적으로 우선하는 스프링 클라우드에 대한 자세한 설명입니다. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!