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. 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: 컬렉션 섹션 아래의 App Configuration 서비스 인스턴스에서 만든 컬렉션의 ID입니다.
    • environmentId : 환경 섹션 아래의 앱 구성 서비스 인스턴스에서 작성된 환경 ID입니다.

init()setContext() 는 초기화 클래스이며 appConfigClient 를 사용하여 한 번만 호출해야 합니다. 초기화된 appConfigClient,는 AppConfiguration.getInstance() 를 사용하여 여러 클래스에서 가져올 수 있습니다. 자세한 내용은 다른 클래스에서 appConfigClient 가져오기 를 참조하세요.

사설 엔드포인트 사용

IBM Cloud 사설 네트워크를 통해서만 액세스할 수 있는 사설 엔드포인트를 사용하여 App Configuration 서비스에 연결하도록 SDK를 설정하십시오.

appConfigClient.usePrivateEndpoint(true);

이는 SDK에서 init 함수를 호출하기 전에 수행해야 합니다.

구성을 위해 지속적 캐시를 사용하는 옵션

애플리케이션이 다시 시작될 때 App Configuration 서비스 중단이라는 드문 시나리오에서도 애플리케이션과 SDK가 계속 작동하도록 하려면 영구 캐시를 사용하여 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 서비스를 사용하면 부울, 숫자, 문자열 데이터 유형으로 기능 플래그 및 특성을 구성할 수 있습니다. 문자열 데이터 유형은 텍스트 문자열, JSON 또는 YAML 형식이 될 수 있습니다. SDK는 각 형식을 처리합니다.

출력 예시
기능 또는 특성 값 데이터 유형 데이터 형식 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();