Spring Cloud Config—提供自定義RestTemplate

稀罕你幹嘛發表於2018-02-28

在某些情況下,您可能需要從客戶端自定義對配置伺服器的請求。通常這涉及傳遞特殊的Authorization標頭來對伺服器的請求進行身份驗證。要提供自定義RestTemplate,請按照以下步驟操作。 設定spring.cloud.config.enabled=false以禁用現有的配置伺服器屬性源。

使用PropertySourceLocator實現建立一個新的配置bean。

CustomConfigServiceBootstrapConfiguration.java @Configuration public class CustomConfigServiceBootstrapConfiguration { @Bean public ConfigClientProperties configClientProperties() { ConfigClientProperties client = new ConfigClientProperties(this.environment); client.setEnabled(false); return client; }

@Bean
public ConfigServicePropertySourceLocator configServicePropertySourceLocator() {
    ConfigClientProperties clientProperties = configClientProperties();
   ConfigServicePropertySourceLocator configServicePropertySourceLocator =  new ConfigServicePropertySourceLocator(clientProperties);
    configServicePropertySourceLocator.setRestTemplate(customRestTemplate(clientProperties));
    return configServicePropertySourceLocator;
}
複製程式碼

} 在resources/META-INF中建立一個名為spring.factories的檔案,並指定您的自定義配置。

spring.factorties org.springframework.cloud.bootstrap.BootstrapConfiguration = com.my.config.client.CustomConfigServiceBootstrapConfiguration Vault 當使用Vault作為配置伺服器的後端時,客戶端將需要為伺服器提供一個令牌,以從Vault中檢索值。可以通過在bootstrap.yml中設定spring.cloud.config.token在客戶端中提供此令牌。

bootstrap.yml spring: cloud: config: token: YourVaultToken Vault Vault中的巢狀金鑰 Vault支援將鍵嵌入儲存在Vault中的值。例如

echo -n '{"appA": {"secret": "appAsecret"}, "bar": "baz"}' | vault write secret/myapp -

此命令將向您的Vault編寫一個JSON物件。要在Spring中訪問這些值,您將使用傳統的點(。)註釋。例如

@Value("${appA.secret}") String name = "World"; 上程式碼將name變數設定為appAsecret。

Spring Cloud Config—提供自定義RestTemplate
對原始碼感興趣的朋友可以加企鵝2147775633

相關文章