Java용 HBase API Hello World

이 예시는 Java용 Bigtable HBase 클라이언트 라이브러리를 사용하는 'hello world' 애플리케이션으로 다음을 수행하는 방법을 보여줍니다.

  • 인증 설정
  • Bigtable 인스턴스에 연결
  • 새 테이블 만들기
  • 테이블에 데이터 쓰기
  • 데이터 다시 읽기
  • 테이블 삭제

인증 설정

로컬 개발 환경에서 이 페이지의 Java 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

  1. Google Cloud CLI를 설치합니다.
  2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

    gcloud auth application-default login

자세한 내용은 로컬 개발 환경의 인증 설정를 참조하세요.

샘플 실행

이 샘플은 HBase API를 사용하여 Bigtable과 통신합니다. 이 샘플의 코드는 GitHub 저장소 GoogleCloudPlatform/cloud-bigtable-examplesjava/hello-world 디렉터리에 있습니다.

이 샘플 프로그램을 실행하려면 GitHub에서 샘플 안내를 따르세요.

HBase API 사용

샘플 애플리케이션을 Bigtable에 연결하여 몇 가지 간단한 작업을 보여줍니다.

클라이언트 라이브러리 설치 및 가져오기

이 샘플은 Maven 뿐만 아니라 Java용 Bigtable HBase 클라이언트를 사용합니다. 클라이언트 라이브러리 사용에 대한 안내를 참조하세요.

이 샘플은 다음 가져오기를 사용합니다.

import com.google.cloud.bigtable.hbase.BigtableConfiguration;
import java.io.IOException;

Bigtable에 연결

BigtableConfiguration 클래스를 사용하여 Bigtable에 연결합니다.

// Create the Bigtable connection, use try-with-resources to make sure it gets closed
try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {

  // The admin API lets us create, manage and delete tables
  Admin admin = connection.getAdmin();

테이블 만들기

Admin API를 사용하여 테이블을 만듭니다.

// Create a table with a single column family
HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(TABLE_NAME));
descriptor.addFamily(new HColumnDescriptor(COLUMN_FAMILY_NAME));

System.out.println("HelloWorld: Create table " + descriptor.getNameAsString());
admin.createTable(descriptor);

테이블에 행 쓰기

Table 클래스를 사용하여 테이블에 행을 입력합니다. 처리량을 높이려면 BigtableBufferedMutator 클래스를 사용해보세요.

// Retrieve the table we just created so we can do some reads and writes
Table table = connection.getTable(TableName.valueOf(TABLE_NAME));

// Write some rows to the table
System.out.println("HelloWorld: Write some greetings to the table");
for (int i = 0; i < GREETINGS.length; i++) {
  // Each row has a unique row key.
  //
  // Note: This example uses sequential numeric IDs for simplicity, but
  // this can result in poor performance in a production application.
  // Since rows are stored in sorted order by key, sequential keys can
  // result in poor distribution of operations across nodes.
  //
  // For more information about how to design a Bigtable schema for the
  // best performance, see the documentation:
  //
  //     https://cloud.google.com/bigtable/docs/schema-design
  String rowKey = "greeting" + i;

  // Put a single row into the table. We could also pass a list of Puts to write a batch.
  Put put = new Put(Bytes.toBytes(rowKey));
  put.addColumn(COLUMN_FAMILY_NAME, COLUMN_NAME, Bytes.toBytes(GREETINGS[i]));
  table.put(put);
}

키를 통해 행 읽기

키를 사용하여 행을 직접 가져옵니다.

// Get the first greeting by row key
String rowKey = "greeting0";
Result getResult = table.get(new Get(Bytes.toBytes(rowKey)));
String greeting = Bytes.toString(getResult.getValue(COLUMN_FAMILY_NAME, COLUMN_NAME));
System.out.println("Get a single greeting by row key");
System.out.printf("\t%s = %s\n", rowKey, greeting);

모든 테이블 행 검색

Scan 클래스를 사용하여 행 범위를 가져옵니다.

// Now scan across all rows.
Scan scan = new Scan();

System.out.println("HelloWorld: Scan for all greetings:");
ResultScanner scanner = table.getScanner(scan);
for (Result row : scanner) {
  byte[] valueBytes = row.getValue(COLUMN_FAMILY_NAME, COLUMN_NAME);
  System.out.println('\t' + Bytes.toString(valueBytes));
}

테이블 삭제

Admin API를 사용하여 테이블을 삭제합니다.

// Clean up by disabling and then deleting the table
System.out.println("HelloWorld: Delete the table");
admin.disableTable(table.getName());
admin.deleteTable(table.getName());

요약 정리

다음은 주석이 없는 전체 예시입니다.


package com.example.bigtable;

import com.google.cloud.bigtable.hbase.BigtableConfiguration;
import java.io.IOException;
import java.util.UUID;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

public class HelloWorld {

  private static final byte[] TABLE_NAME =
      Bytes.toBytes("Hello-Bigtable-" + UUID.randomUUID().toString().substring(0, 19));
  private static final byte[] COLUMN_FAMILY_NAME = Bytes.toBytes("cf1");
  private static final byte[] COLUMN_NAME = Bytes.toBytes("greeting");

  private static final String[] GREETINGS = {
    "Hello World!", "Hello Cloud Bigtable!", "Hello HBase!"
  };

  protected static void doHelloWorld(String projectId, String instanceId) {

    try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {

      Admin admin = connection.getAdmin();

      try {
        HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(TABLE_NAME));
        descriptor.addFamily(new HColumnDescriptor(COLUMN_FAMILY_NAME));

        System.out.println("HelloWorld: Create table " + descriptor.getNameAsString());
        admin.createTable(descriptor);

        Table table = connection.getTable(TableName.valueOf(TABLE_NAME));

        System.out.println("HelloWorld: Write some greetings to the table");
        for (int i = 0; i < GREETINGS.length; i++) {
          String rowKey = "greeting" + i;

          Put put = new Put(Bytes.toBytes(rowKey));
          put.addColumn(COLUMN_FAMILY_NAME, COLUMN_NAME, Bytes.toBytes(GREETINGS[i]));
          table.put(put);
        }

        String rowKey = "greeting0";
        Result getResult = table.get(new Get(Bytes.toBytes(rowKey)));
        String greeting = Bytes.toString(getResult.getValue(COLUMN_FAMILY_NAME, COLUMN_NAME));
        System.out.println("Get a single greeting by row key");
        System.out.printf("\t%s = %s\n", rowKey, greeting);

        Scan scan = new Scan();

        System.out.println("HelloWorld: Scan for all greetings:");
        ResultScanner scanner = table.getScanner(scan);
        for (Result row : scanner) {
          byte[] valueBytes = row.getValue(COLUMN_FAMILY_NAME, COLUMN_NAME);
          System.out.println('\t' + Bytes.toString(valueBytes));
        }

        System.out.println("HelloWorld: Delete the table");
        admin.disableTable(table.getName());
        admin.deleteTable(table.getName());
      } catch (IOException e) {
        if (admin.tableExists(TableName.valueOf(TABLE_NAME))) {
          System.out.println("HelloWorld: Cleaning up table");
          admin.disableTable(TableName.valueOf(TABLE_NAME));
          admin.deleteTable(TableName.valueOf(TABLE_NAME));
        }
        throw e;
      }
    } catch (IOException e) {
      System.err.println("Exception while running HelloWorld: " + e.getMessage());
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    String projectId = requiredProperty("bigtable.projectID");
    String instanceId = requiredProperty("bigtable.instanceID");

    doHelloWorld(projectId, instanceId);
  }

  private static String requiredProperty(String prop) {
    String value = System.getProperty(prop);
    if (value == null) {
      throw new IllegalArgumentException("Missing required system property: " + prop);
    }
    return value;
  }
}