Java 用 App Configuration サーバー SDK

App Configuration サービスは、アプリケーション、マイクロサービス、分散環境と統合される SDK を提供します。

Java 用サーバー SDK の統合

App Configuration サービスは、Java アプリケーションと統合される SDK を提供します。 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. App Configuration サービス・インスタンスと接続するように SDK を初期化します。

    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-southau-syd など。
    • guid: App Configuration サービスの GUID。 App Configuration サービス・ダッシュボードのサービス資格情報セクションから取得してください。
    • apiKey App Configuration サービスの。 ApiKey App Configuration サービス・ダッシュボードのサービス資格情報セクションから取得してください。
    • collectionId:Collectionsセクションの App Configuration サービスインスタンスで作成されたコレクションのID。
    • environmentId:「環境」セクションの下のアプリ構成サービス・インスタンスで作成された環境の ID。

init() および setContext() は初期化クラスであり、 appConfigClient を使用して 1 回だけ 呼び出す必要があります。 appConfigClient,が初期化されると、AppConfiguration.getInstance() を使うことで、クラス間で取得できます。 詳しくは、他のクラスをまたがってappConfigClientを取得する を参照してください。

プライベート・エンドポイントの使用

IBM Cloud プライベート・ネットワークを介してのみアクセス可能なプライベート・エンドポイントを使用して、 App Configuration サービスに接続するように SDK を設定します。

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 ポッドが再始動され、キャッシュ・ファイル (appconfiguration.json) がポッドの一時ボリュームに保管された場合を考えてみます。 ポッドが再始動すると、kubernetes はポッド内の 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 サービスでは、ブール値、数値、文字列の各データ・タイプを使用して機能フラグとプロパティーを構成できます。 「文字列」データ・タイプは、テキスト文字列、JSON、YAML のフォーマットにできます。 SDKは表1に示すように各 フォーマットを表1に示すように処理する。

出力例
フィーチャーまたはプロパティーの値 データ型 データ形式 GetCurrentValue() によって返されるデータのタイプ 出力例
true BOOLEAN 適用外 bool true
25 NUMERIC 適用外 float64 25
"a string text" STRING TEXT string a string text
{"firefox": {
"name": "Firefox",
"pref_url": "about:config"
}}
ストリング JSON map[string]interface{} map[browsers:map[firefox:map[name:Firefox pref_url:about:config]]]
men:
- John Smith
- Bill Jones ¥ n 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 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();