App Configuration 伺服器 SDK for Java

App Configuration 服務提供 SDK,可與應用程式、微服務及分散式環境整合。

整合伺服器 SDK for Java

App Configuration 服務提供 SDK,以與 Java 應用程式整合。 您可以整合 App Configuration SDK 來評估特性旗標的值。

  1. 以下列其中一種方式安裝 SDK。

    使用 Maven

    <dependency>
       <groupId>com.ibm.cloud</groupId>
       <artifactId>appconfiguration-java-sdk</artifactId>
       <version>0.3.3</version>
    </dependency>
    

    透過新增下列指令,透過 Gradle 取得套件:

    implementation group: 'com.ibm.cloud', name: 'appconfiguration-java-sdk', version: '0.3.3'
    
  2. 在 Java 微服務或應用程式中,包含 SDK:

    import com.ibm.cloud.appconfiguration.sdk.AppConfiguration;
    
  3. 起始設定 SDK 以使用 App Configuration 服務實例進行連接。

    String region = AppConfiguration.REGION_US_SOUTH;
    String guid = "guid";
    String apikey = "apikey";
    
    String collectionId = "airlines-webapp";
    String environmentId = "dev";
    
    AppConfiguration appConfigClient = AppConfiguration.getInstance();
    appConfigClient.init(region, guid, apikey);
    appConfigClient.setContext(collectionId, environmentId);
    

    其中,

    • region:建立 App Configuration 服務實體的區域名稱。 請參閱 此處 的支援地點清單。 例如:- us-south, au-syd 等。
    • guid: App Configuration 服務的 GUID。 請從 App Configuration 服務儀表板的服務認證區段取得它。
    • apiKey: App Configuration 服務的 ApiKey。 請從 App Configuration 服務儀表板的服務認證區段取得它。
    • collectionId: 在 Collections 區段下 App Configuration 服務實例中建立的集合 ID。
    • environmentId: 在 App Configuration 服務實例的「環境」區段下建立的環境 ID。

init()setContext() 是起始設定類別,且必須 只呼叫一次 (使用 appConfigClient)。 appConfigClient,初始化時可以使用 AppConfiguration.getInstance() 跨類別取得。 有關更多信息,請 參閱跨其他類別獲取appConfigClient

使用專用端點

設定 SDK,以使用只能透過 IBM Cloud 專用網路存取的專用端點來連接至 App Configuration 服務。

appConfigClient.usePrivateEndpoint(true);

在 SDK 上呼叫 init 函數之前,必須先完成此動作。

使用持續性快取進行配置的選項

為了讓您的應用程式及 SDK 在 App Configuration 服務關閉時間的罕見實務期間繼續作業,在應用程式重新啟動之後,您可以使用持續性快取將 SDK 配置為運作。 SDK 使用持續性快取來儲存應用程式重新啟動時可用的 App Configuration 資料。

// 1. default (without persistent cache)
    appConfigClient.setContext(collectionId, environmentId);

// 2. optional (with persistent cache)
    ConfigurationOptions configOptions = new ConfigurationOptions();
    configOptions.setPersistentCacheDirectory("/var/lib/docker/volumes/");
    appConfigClient.setContext(collectionId, environmentId, configOptions);

其中:

  • persistentCacheDirectory: 具有使用者讀取及寫入權之目錄的絕對路徑。 SDK 會在指定的目錄中建立檔案- appconfiguration.json,並用作持續性快取來儲存 App Configuration 服務資訊。

當啟用持續快取時,SDK 會在持續快取中保留前次已知的良好配置。 如果無法呼叫到 App Configuration 伺服器,則持續性快取中的最新配置會載入至應用程式以繼續運作。

請確保在任何情況下都不會遺失或刪除快取檔。 例如,假設 Kubernetes Pod 重新啟動,且快取檔 (appconfiguration.json) 儲存在 Pod 的暫時磁區中。 當 Pod 重新啟動時,kubernetes 會毀損 Pod 中的 ephermal 磁區,因此會刪除快取檔。 因此,請提供持續性目錄的正確絕對路徑,確定 SDK 所建立的快取檔一律儲存在持續性磁區中。

離線選項

SDK 也設計為提供配置,並執行特性旗標及內容評估,而不連接至 App Configuration 服務。

ConfigurationOptions configOptions = new ConfigurationOptions();
configOptions.setBootstrapFile("saflights/flights.json");
configOptions.setLiveConfigUpdateEnabled(false);
appConfigClient.setContext(collectionId, environmentId, configOptions);

其中:

  • bootstrapFile:JSON 檔案的絕對路徑,包含配置詳細資料。 請務必提供適當的 JSON 檔案。 您可以使用 IBM Cloud App Configuration CLI 的 ibmcloud ac export 指令來產生此檔案。
  • liveConfigUpdateEnabled: 從伺服器進行即時配置更新。 如果不得從伺服器提取新的配置值,請將此值設為 false。 預設值為 true

使用特性和內容相關 API 的範例

請參閱下列範例,以使用特性及內容相關 API。

取得單一特性

Feature feature = appConfigClient.getFeature("online-check-in");

if (feature != null) {
    System.out.println("Feature Name : " + feature.getFeatureName());
    System.out.println("Feature Id : " + feature.getFeatureId());
    System.out.println("Feature Type : " + feature.getFeatureDataType());
    System.out.println("Is feature enabled? : " + feature.isEnabled());
}

取得所有特性

HashMap<String, Feature> features = appConfigClient.getFeatures();

特性評估

您可以使用 feature.getCurrentValue(entityId, entityAttributes) 方法來評估特性旗標的值。 您必須傳遞唯一的 entityId 作為特性旗標評估的參數。 如果特性旗標配置了 App Configuration 服務中的區段,您可以將屬性值設為 JSONObject。

String entityId = "john_doe";
JSONObject entityAttributes = new JSONObject();
entityAttributes.put("city", "Bangalore");
entityAttributes.put("country", "India");

String value = (String) feature.getCurrentValue(entityId, entityAttributes);
  • entityId: 實體的 ID。 這是與用來評估特性的實體相關的字串 ID。 例如,實體可能是在行動式裝置上執行的應用程式實例、在雲端上執行的微服務,或執行該微服務之基礎架構的元件。 若要讓任何實體與 App Configuration互動,它必須提供唯一實體 ID。

  • entityAttributes: JSON 物件,由定義指定實體的屬性名稱及其值組成。 如果特性旗標未配置任何目標定義,則這是選用參數。 如果已配置目標,則應該提供 entityAttributes 以進行規則評估。 屬性是用來定義區段的參數。 SDK 會使用屬性值來判斷指定的實體是否滿足目標規則,並傳回適當的特性旗標值。

取得單一內容

Property property = appConfigClient.getProperty("check-in-charges");

if (property != null) {
    System.out.println("Property Name : " + property.getPropertyName());
    System.out.println("Property Id : " + property.getPropertyId());
    System.out.println("Property Type : " + property.getPropertyDataType());
}

取得所有內容

HashMap<String, Property> property = appConfigClient.getProperties();

內容評估

您可以使用 property.getCurrentValue(entityId, entityAttributes) 方法來評估內容的值。 此方法會根據評估傳回預設內容值或其置換值。

String entityId = "john_doe";
JSONObject entityAttributes = new JSONObject();
entityAttributes.put("city", "Bangalore");
entityAttributes.put("country", "India");

String value = (String) property.getCurrentValue(entityId, entityAttributes);
  • entityId: 實體的 ID。 這是與評估內容所依據的實體相關的字串 ID。 例如,實體可能是在行動式裝置上執行的應用程式實例、在雲端上執行的微服務,或執行該微服務之基礎架構的元件。 若要讓任何實體與 App Configuration互動,它必須提供唯一實體 ID。

  • entityAttributes: JSON 物件,由定義指定實體的屬性名稱及其值組成。 如果內容未配置任何目標定義,則這是選用參數。 如果已配置目標,則應該提供 entityAttributes 以進行規則評估。 屬性是用來定義區段的參數。 SDK 會使用屬性值來判斷指定的實體是否滿足目標規則,並傳回適當的內容值。

跨其他類別提取 appConfigClient

起始設定 SDK 時,可以跨其他類別取得 appConfigClient,如下所示:

// **other classes**

import com.ibm.cloud.appconfiguration.sdk.AppConfiguration;
AppConfiguration appConfigClient = AppConfiguration.getInstance();

Feature feature = appConfigClient.getFeature("string-feature");
boolean enabled = feature.isEnabled();
String featureValue = (String) feature.getCurrentValue(entityId, entityAttributes);

支援的資料類型

App Configuration 服務可讓您使用下列資料類型來配置特性旗標及內容: 布林、數值、字串。 「字串」資料類型可以是 TEXT 字串、JSON 或 YAML 格式。 SDK 處理每一種格式,如表 1 所示。

輸出範例
特性或內容值 資料類型 資料格式 GetCurrentValue() 傳回的資料類型 輸出範例
true BOOLEAN 不適用 bool true
25 NUMERIC 不適用 float64 25
「字串文字」 STRING TEXT string a string text
{"firefox": {
"name": "Firefox",
"pref_url": "about:config"
}}
STRING JSON map[string]interface{} map[browsers:map[firefox:map[name:Firefox pref_url:about:config]]]
men:
- John Smith
- Bill Jones
women:
- Mary Smith
- Susan Williams
STRING YAML java.lang.String

`"men:

  • John Smith
  • Bill Jones\women:
  • Mary Smith
  • Susan Williams"`

特性旗標

Feature feature = appConfigClient.getFeature("json-feature");
if (feature != null) {
   feature.getFeatureDataType();       // STRING
   feature.getFeatureDataFormat();     // JSON
   feature.getCurrentValue(entityId, entityAttributes); // JSONObject or JSONArray is returned
}

// Example Below
// input json :- [{"role": "developer", "description": "do coding"},{"role": "tester", "description": "do testing"}]
// expected output :- "do coding"

JSONArray tar_val = (JSONArray) feature.get_current_value(entityId, entityAttributes);
String expected_output = (String) ((JSONObject) tar_val.get(0)).get('description');

// input json :- {"role": "tester", "description": "do testing"}
// expected output :- "tester"

JSONObject tar_val = (JSONObject) feature.get_current_value(entityId, entityAttributes);
String expected_output = (String) tar_val.get('role');

Feature feature = appConfigClient.getFeature("yaml-feature");
if (feature != null) {
   feature.getFeatureDataType();       // STRING
   feature.getFeatureDataFormat();     // YAML
   feature.getCurrentValue(entityId, entityAttributes); // Yaml String is returned
}

內容

Property property = appConfigClient.getProperty("json-property");
if (property != null) {
   property.getPropertyDataType();     // STRING
   property.getPropertyDataFormat();   // JSON
   property.getCurrentValue(entityId, entityAttributes); // JSONObject or JSONArray is returned
}

// Example Below
// input json :- [{"role": "developer", "description": "do coding"},{"role": "tester", "description": "do testing"}]
// expected output :- "do coding"

JSONArray tar_val = (JSONArray) property.get_current_value(entityId, entityAttributes);
String expected_output = (String) ((JSONObject) tar_val.get(0)).get('description');

// input json :- {"role": "tester", "description": "do testing"}
// expected output :- "tester"

JSONObject tar_val = (JSONObject) property.get_current_value(entityId, entityAttributes);
String expected_output = (String) tar_val.get('role');

Property property = appConfigClient.getProperty("yaml-property");
if (property != null) {
   property.getPropertyDataType();     // STRING
   property.getPropertyDataFormat();   // YAML
   property.getCurrentValue(entityId, entityAttributes); // Yaml String is returned
}

設定特性或內容變更的接聽器

SDK 提供當特性旗標或內容的配置變更時,即時通知您的機制。 您可以使用相同的appConfigClient訂閱配置變更。

appConfigClient.registerConfigurationUpdateListener(new ConfigurationUpdateListener() {
   @Override
   public void onConfigurationUpdate() {
      System.out.println("Received updated configurations");
      // **add your code**
      // To find the effect of any configuration changes, you can call the feature or property related methods

      // Feature feature = appConfigClient.getFeature("numeric-feature");
      // Integer newValue = (Integer) feature.getCurrentValue(entityId, entityAttributes);
   }
});

提取最新資料

appConfigClient.fetchConfigurations();