Spring Cloudt整合Netflix Archaius之多數(shù)據(jù)源

1.概述

Netflix Archaius提供了用于連接許多數(shù)據(jù)源的類庫和功能仁连。

在本教程中限府,我們將學(xué)習(xí)如何獲取配置:

  • 使用JDBC API連接到數(shù)據(jù)庫
  • 讀取來自存儲(chǔ)在DynamoDB實(shí)例中的配置
  • 通過Zookeeper配置為動(dòng)態(tài)分布式配置

有關(guān)Netflix Archaius的介紹秃嗜,請(qǐng)查看本文惑申。

2.將Netflix Archaius與JDBC連接一起使用

正如我們?cè)诮榻B性教程中所解釋的岩睁,每當(dāng)我們希望Archaius處理配置時(shí)歧寺,我們都需要?jiǎng)?chuàng)建一個(gè)Apache的AbstractConfiguration bean燥狰。

Bean將由Spring Cloud Bridge自動(dòng)捕獲并添加到Archaius的Composite Configuration堆棧中。

2.1 依賴

使用JDBC連接到數(shù)據(jù)庫所需的所有功能都包含在核心庫中斜筐,因此除了我們?cè)诮榻B性教程中提到的那些之外龙致,我們不需要任何額外的依賴:

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

2.2 如何創(chuàng)建配置Bean

在這種情況下,我們需要使用JDBCConfigurationSource實(shí)例創(chuàng)建AbstractConfiguration bean 顷链。

為了說明如何從JDBC數(shù)據(jù)庫獲取值目代,我們必須指定:

  • 一個(gè)javax.sql.Datasource對(duì)象
  • 一個(gè)SQL查詢字符串,它將使用配置的鍵及其對(duì)應(yīng)的值檢索至少兩列
  • 兩列分別表示屬性鍵和值

讓我們繼續(xù)創(chuàng)建這個(gè)bean:

@Autowired
DataSource h2DataSource;

@Bean
public AbstractConfiguration addApplicationPropertiesSource() {
    PolledConfigurationSource source = new JDBCConfigurationSource(h2DataSource,
            "select distinct key, value from properties", "key", "value");
    return new DynamicConfiguration(source, new FixedDelayPollingScheduler());
}

2.3 示例

為了保持簡單并且仍然有一個(gè)操作示例嗤练,我們將使用一些初始數(shù)據(jù)設(shè)置H2內(nèi)存數(shù)據(jù)庫實(shí)例榛了。

為此,我們首先添加必要的依賴項(xiàng):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

接下來煞抬,我們將聲明將包含我們的屬性的JPA實(shí)體:

@Entity
public class Properties {

    @Id
    private String key;

    @SuppressWarnings("unused")
    private String value;
}

我們將在我們的資源中包含一個(gè)data.sql文件霜大,用一些初始值填充內(nèi)存數(shù)據(jù)庫:

insert into properties
values('springcloud.archaius.properties.one', 'one FROM:jdbc_source');

insert into properties
values('springcloud.archaius.properties.three', 'three FROM:jdbc_source');

最后,要檢查任何給定點(diǎn)的屬性值革答,我們可以創(chuàng)建一個(gè)端點(diǎn)來檢索由Archaius管理的值:

@RestController
public class ConfigPropertiesController {

    private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance()
            .getStringProperty("springcloud.archaius.properties.one", "not found!");

    private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance()
            .getStringProperty("springcloud.archaius.properties.two", "not found!");

    private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance()
            .getStringProperty("springcloud.archaius.properties.three", "not found!");

    @GetMapping("/properties-from-dynamic")
    public Map<String, String> getPropertiesFromDynamic() {
        Map<String, String> properties = new HashMap<>();
        properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get());
        properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get());
        properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get());
        return properties;
    }
}

如果數(shù)據(jù)在任何時(shí)候發(fā)生變化战坤,Archaius將在運(yùn)行時(shí)檢測(cè)到它并開始檢索新值曙强。

訪問地址 http://localhost:8082/properties-from-dynamic

運(yùn)行結(jié)果

3.如何使用DynamoDB實(shí)例創(chuàng)建配置源

DynamoDB是AWS上完全托管的NoSQL數(shù)據(jù)庫,類似于其他NoSQL數(shù)據(jù)庫湖笨,如Cassandra或MongoDB旗扑。DynamoDB提供快速,一致和可預(yù)測(cè)的性能慈省,并且具有大規(guī)耐畏溃可擴(kuò)展性。

首先需要在本地啟動(dòng)DynamoDB實(shí)例边败「ぶ裕可從官網(wǎng)下載dynamodb_local_latest.zip。

解壓后在命令行中輸入下面命令啟動(dòng)

 java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb

3.1 依賴

我們將以下庫添加到我們的pom.xml文件中:

<dependencies>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-dynamodb</artifactId>
    </dependency>
    <dependency>
        <groupId>com.github.derjust</groupId>
        <artifactId>spring-data-dynamodb</artifactId>
        <version>${spring.dynamo.version}</version>
    </dependency>
    <dependency>
        <groupId>com.netflix.archaius</groupId>
        <artifactId>archaius-aws</artifactId>
        <version>${archaius.version}</version>
    </dependency>
</dependencies>

<properties>
    <spring.dynamo.version>4.5.0</spring.dynamo.version>
    <archaius.version>0.7.6</archaius.version>
</properties>

在 AWS-java的SDK-dynamodb依存庫將允許我們建立DynamoDB客戶端連接到數(shù)據(jù)庫笑窜。

使用 spring-data-dynamodb庫致燥,我們將設(shè)置DynamoDB存儲(chǔ)庫。

最后排截,我們將使用archaius-aws庫來創(chuàng)建AbstractConfiguration嫌蚤。

3.2 使用DynamoDB作為配置源

這次,將使用DynamoDbConfigurationSource對(duì)象創(chuàng)建AbstractConfiguration :

@Autowired
AmazonDynamoDB amazonDynamoDb;

@Bean
public AbstractConfiguration addApplicationPropertiesSource() {
    initDatabase();
    PolledConfigurationSource source = new DynamoDbConfigurationSource(amazonDynamoDb);
    return new DynamicConfiguration(source, new FixedDelayPollingScheduler());
}

默認(rèn)情況下断傲,Archaius會(huì)搜索名為“archaiusProperties”的表脱吱,其中包含Dynamo數(shù)據(jù)庫中的“key”和“value”屬性,以用作源认罩。

如果我們想要覆蓋這些值箱蝠,我們必須聲明以下系統(tǒng)屬性:

  • com.netflix.config.dynamo.tableName
  • com.netflix.config.dynamo.keyAttributeName
  • com.netflix.config.dynamo.valueAttributeName

3.3 創(chuàng)建一個(gè)功能齊全的示例

我們將首先安裝一個(gè)本地DynamoDB實(shí)例來輕松測(cè)試功能。

要使用一些初始數(shù)據(jù)填充數(shù)據(jù)庫垦垂,我們將首先創(chuàng)建一個(gè)DynamoDBTable實(shí)體來映射數(shù)據(jù):

@DynamoDBTable(tableName = "archaiusProperties")
public class ArchaiusProperties {

    @DynamoDBHashKey
    @DynamoDBAttribute
    private String key;

    @DynamoDBAttribute
    private String value;
}

接下來宦搬,我們將為此實(shí)體創(chuàng)建一個(gè)CrudRepository:

public interface ArchaiusPropertiesRepository extends CrudRepository<ArchaiusProperties, String> {

}

最后,我們將使用存儲(chǔ)庫和AmazonDynamoDB實(shí)例創(chuàng)建表并在之后插入數(shù)據(jù):

@Autowired
AmazonDynamoDB amazonDynamoDb;

@Autowired
private ArchaiusPropertiesRepository repository;

private void initDatabase() {
   // Create the table
   DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDb);
   CreateTableRequest tableRequest = mapper.generateCreateTableRequest(ArchaiusProperties.class);
   tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
   TableUtils.createTableIfNotExists(amazonDynamoDb, tableRequest);

   // Populate the table
   ArchaiusProperties property = new ArchaiusProperties("springcloud.archaius.properties.one", "one FROM:dynamoDB");
   ArchaiusProperties property3 = new ArchaiusProperties("springcloud.archaius.properties.three", "three FROM:dynamoDB");
   repository.save(Arrays.asList(property, property3));
}

我們可以在創(chuàng)建DynamoDbConfigurationSource之前調(diào)用此方法劫拗。

4.如何設(shè)置動(dòng)態(tài)Zookeeper分布式配置

使用Zookeeper的一個(gè)好處是可以將它用作分布式配置存儲(chǔ)间校。

如果我們將它與Archaius結(jié)合起來,我們最終會(huì)得到一個(gè)靈活且可擴(kuò)展的配置管理解決方案杨幼。

4.1 依賴

讓我們按照Spring Cloud的官方說明設(shè)置Apache的Zookeeper穩(wěn)定的版本撇簿。

唯一的區(qū)別是我們只需要Zookeeper提供的部分功能,因此我們可以使用spring-cloud-starter-zookeeper-config依賴差购,而不是官方指南中使用的依賴:

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zookeeper-config</artifactId>
        <version>${cloud.zookeeper.version}</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.zookeeper</groupId>
                <artifactId>zookeeper</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>${zookeeper.version}</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    </dependencies>
    
    <properties>
    <cloud.zookeeper.version>2.0.0.RELEASE</cloud.zookeeper.version>
    <zookeeper.version>3.4.13</zookeeper.version>
    </properties>

4.2 Spring Cloud的自動(dòng)配置

正如官方文檔中所解釋的那樣四瘫,包括spring-cloud-starter-zookeeper-config依賴關(guān)系足以設(shè)置Zookeeper屬性源。

默認(rèn)情況下欲逃,只有一個(gè)源是自動(dòng)配置的找蜜,在config / application Zookeeper節(jié)點(diǎn)下搜索屬性 。因此稳析,此節(jié)點(diǎn)用作不同應(yīng)用程序之間的共享配置源洗做。

此外弓叛,如果我們使用spring.application.name屬性指定應(yīng)用程序名稱,則會(huì)自動(dòng)配置另一個(gè)源诚纸,這次在config/<app_name>節(jié)點(diǎn)中搜索屬性 撰筷。

這些父節(jié)點(diǎn)下的每個(gè)節(jié)點(diǎn)名稱將指示屬性鍵,其數(shù)據(jù)將是屬性值畦徘。

幸運(yùn)的是毕籽,由于Spring Cloud將這些屬性源添加到上下文中,因此Archaius會(huì)自動(dòng)管理它們井辆。無需以編程方式創(chuàng)建AbstractConfiguration关筒。

4.3 準(zhǔn)備初始數(shù)據(jù)

在這種情況下,我們還需要一個(gè)本地Zookeeper服務(wù)器來將配置存儲(chǔ)為節(jié)點(diǎn)杯缺。我們可以按照Apache的指南來設(shè)置在端口2181上運(yùn)行的獨(dú)立服務(wù)器蒸播。

要連接到Zookeeper服務(wù)并創(chuàng)建一些初始數(shù)據(jù),我們將使用 Apache的Curator客戶端:

@Component
public class ZookeeperConfigsInitializer {
     private static final String CONFIG_BASE_NODE_PATH = "/config";
        private static final String APPLICATION_BASE_NODE_PATH = CONFIG_BASE_NODE_PATH + "/application";

        @Autowired
        CuratorFramework client;

        @EventListener
        public void appReady(ApplicationReadyEvent event) throws Exception {
            String pathOne = APPLICATION_BASE_NODE_PATH + "/springcloud.archaius.properties.one";
            String valueOne = "one FROM:zookeeper";
            String pathThree = APPLICATION_BASE_NODE_PATH + "/springcloud.archaius.properties.three";
            String valueThree = "three FROM:zookeeper";
            createBaseNodes();
            setValue(pathOne, valueOne);
            setValue(pathThree, valueThree);
        }

        private void setValue(String path, String value) throws Exception {
            if (client.checkExists()
                .forPath(path) == null) {
                client.create()
                    .forPath(path, value.getBytes());
            } else {
                client.setData()
                    .forPath(path, value.getBytes());
            }
        }

        private void createBaseNodes() throws Exception {
            if (client.checkExists()
                .forPath(CONFIG_BASE_NODE_PATH) == null) {
                client.create()
                    .forPath(CONFIG_BASE_NODE_PATH);
            }
            if (client.checkExists()
                .forPath(APPLICATION_BASE_NODE_PATH) == null) {
                client.create()
                    .forPath(APPLICATION_BASE_NODE_PATH);
            }
        }
}

我們可以檢查日志以查看屬性源萍肆,以驗(yàn)證Netflix Archaius在更改后是否刷新了屬性袍榆。

5.結(jié)論

在本文中,我們已經(jīng)了解了如何使用Netflix Archaius設(shè)置高級(jí)配置源塘揣。我們必須考慮到它還支持其他來源蜡塌,例如Etcd,Typesafe勿负,AWS S3文件和JCloud。

可以在Github倉庫中看到完整示例劳曹。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末奴愉,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子铁孵,更是在濱河造成了極大的恐慌锭硼,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,542評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蜕劝,死亡現(xiàn)場(chǎng)離奇詭異檀头,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)岖沛,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,596評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門暑始,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人婴削,你說我怎么就攤上這事廊镜。” “怎么了唉俗?”我有些...
    開封第一講書人閱讀 158,021評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵嗤朴,是天一觀的道長配椭。 經(jīng)常有香客問我,道長雹姊,這世上最難降的妖魔是什么股缸? 我笑而不...
    開封第一講書人閱讀 56,682評(píng)論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮吱雏,結(jié)果婚禮上敦姻,老公的妹妹穿的比我還像新娘。我一直安慰自己坎背,他們只是感情好替劈,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,792評(píng)論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著得滤,像睡著了一般陨献。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上懂更,一...
    開封第一講書人閱讀 49,985評(píng)論 1 291
  • 那天眨业,我揣著相機(jī)與錄音,去河邊找鬼沮协。 笑死龄捡,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的慷暂。 我是一名探鬼主播聘殖,決...
    沈念sama閱讀 39,107評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼行瑞!你這毒婦竟也來了奸腺?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,845評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤血久,失蹤者是張志新(化名)和其女友劉穎突照,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體氧吐,經(jīng)...
    沈念sama閱讀 44,299評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡讹蘑,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,612評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了筑舅。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片座慰。...
    茶點(diǎn)故事閱讀 38,747評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖翠拣,靈堂內(nèi)的尸體忽然破棺而出角骤,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 34,441評(píng)論 4 333
  • 正文 年R本政府宣布邦尊,位于F島的核電站背桐,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏蝉揍。R本人自食惡果不足惜链峭,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,072評(píng)論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望又沾。 院中可真熱鬧弊仪,春花似錦、人聲如沸杖刷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,828評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽滑燃。三九已至役听,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間表窘,已是汗流浹背典予。 一陣腳步聲響...
    開封第一講書人閱讀 32,069評(píng)論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留乐严,地道東北人瘤袖。 一個(gè)月前我還...
    沈念sama閱讀 46,545評(píng)論 2 362
  • 正文 我出身青樓,卻偏偏與公主長得像昂验,于是被迫代替她去往敵國和親捂敌。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,658評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理既琴,服務(wù)發(fā)現(xiàn)黍匾,斷路器,智...
    卡卡羅2017閱讀 134,637評(píng)論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,778評(píng)論 6 342
  • 原文鏈接:https://docs.spring.io/spring-boot/docs/1.4.x/refere...
    pseudo_niaonao閱讀 4,680評(píng)論 0 9
  • 20歲后磕诊,你過得日子是你想要的嗎填物?是喜歡還是厭倦了如今的日子呢? 今天與朋友又來了一次說走就走的旅行霎终,大抵人滞磺,在一...
    伊人兒閱讀 1,855評(píng)論 16 36
  • 在中央提出“房子是用來住的击困,不是用來炒的”確定了房地產(chǎn)市場(chǎng)向著打擊投機(jī)、防止熱炒的方向推進(jìn)。2016年阅茶,全國多個(gè)城...
    哈思琪閱讀 302評(píng)論 0 0