자바 Hello World

이 코드 샘플은 Java용 Bigtable 클라이언트 라이브러리를 통해 Java로 작성된 'hello world' 애플리케이션입니다. 이 샘플은 다음 작업을 완료하는 방법을 보여줍니다.

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

인증 설정

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

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

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

    gcloud auth application-default login

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

샘플 실행

이 코드는 Java용 Google Cloud 클라이언트 라이브러리에서 Google Cloud Bigtable 라이브러리를 사용하여 Bigtable과 통신합니다.

시작하기 전에 GitHub의 Google Cloud Platform 샘플 안내를 따릅니다.

Cloud 클라이언트 라이브러리를 Bigtable과 함께 사용

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

Bigtable에 연결

시작하려면 데이터 API 클라이언트 라이브러리와 통신하는 데 사용할 데이터 클라이언트 그리고 Admin API 클라이언트 라이브러리와 통신하는 데 사용할 테이블 관리 클라이언트가 필요합니다.

먼저 hello world 애플리케이션에서 사용할 프로젝트 ID와 인스턴스 ID가 포함된 BigtableDataSettings 객체를 인스턴스화합니다. 그런 다음 설정을 BigtableDataClient.create() 메서드에 전달하여 데이터 클라이언트를 만듭니다.

마찬가지로 관리 클라이언트의 경우에도 먼저 BigtableTableAdminSettings 객체를 만들어 설정을 구성한 후 이 설정을 사용하여 BigtableTableAdminClient 객체를 만듭니다.

Bigtable을 사용할 때는 항상 클라이언트를 한 번 만들고 애플리케이션 전체에서 다시 사용하는 것이 가장 좋습니다.

// Creates the settings to configure a bigtable data client.
BigtableDataSettings settings =
    BigtableDataSettings.newBuilder().setProjectId(projectId).setInstanceId(instanceId).build();

// Creates a bigtable data client.
dataClient = BigtableDataClient.create(settings);

// Creates the settings to configure a bigtable table admin client.
BigtableTableAdminSettings adminSettings =
    BigtableTableAdminSettings.newBuilder()
        .setProjectId(projectId)
        .setInstanceId(instanceId)
        .build();

// Creates a bigtable table admin client.
adminClient = BigtableTableAdminClient.create(adminSettings);

테이블 만들기

테이블을 만들려면 CreateTableRequest 객체를 빌드하고 관리 클라이언트의 createTable() 메서드에 전달합니다.

// Checks if table exists, creates table if does not exist.
if (!adminClient.exists(tableId)) {
  System.out.println("Creating table: " + tableId);
  CreateTableRequest createTableRequest =
      CreateTableRequest.of(tableId).addFamily(COLUMN_FAMILY);
  adminClient.createTable(createTableRequest);
  System.out.printf("Table %s created successfully%n", tableId);
}

테이블에 행 쓰기

세 가지 간단한 인사말이 포함된 greetings[] 문자열 배열을 데이터의 소스로 사용하여 테이블에 작성합니다. 배열을 반복합니다. 반복할 때마다 RowMutation 객체를 만들고 setCell() 메서드를 사용하여 항목을 변형에 추가합니다.

try {
  System.out.println("\nWriting some greetings to the table");
  String[] names = {"World", "Bigtable", "Java"};
  for (int i = 0; i < names.length; i++) {
    String greeting = "Hello " + names[i] + "!";
    RowMutation rowMutation =
        RowMutation.create(tableId, ROW_KEY_PREFIX + i)
            .setCell(COLUMN_FAMILY, COLUMN_QUALIFIER_NAME, names[i])
            .setCell(COLUMN_FAMILY, COLUMN_QUALIFIER_GREETING, greeting);
    dataClient.mutateRow(rowMutation);
    System.out.println(greeting);
  }
} catch (NotFoundException e) {
  System.err.println("Failed to write to non-existent table: " + e.getMessage());
}

row key를 통해 행 읽기

처음으로 쓴 행을 데이터 클라이언트의 readRow() 메서드를 사용하여 읽습니다.

try {
  System.out.println("\nReading a single row by row key");
  Row row = dataClient.readRow(tableId, ROW_KEY_PREFIX + 0);
  System.out.println("Row: " + row.getKey().toStringUtf8());
  for (RowCell cell : row.getCells()) {
    System.out.printf(
        "Family: %s    Qualifier: %s    Value: %s%n",
        cell.getFamily(), cell.getQualifier().toStringUtf8(), cell.getValue().toStringUtf8());
  }
  return row;
} catch (NotFoundException e) {
  System.err.println("Failed to read from a non-existent table: " + e.getMessage());
  return null;
}
try {
  System.out.println("\nReading specific cells by family and qualifier");
  Row row = dataClient.readRow(tableId, ROW_KEY_PREFIX + 0);
  System.out.println("Row: " + row.getKey().toStringUtf8());
  List<RowCell> cells = row.getCells(COLUMN_FAMILY, COLUMN_QUALIFIER_NAME);
  for (RowCell cell : cells) {
    System.out.printf(
        "Family: %s    Qualifier: %s    Value: %s%n",
        cell.getFamily(), cell.getQualifier().toStringUtf8(), cell.getValue().toStringUtf8());
  }
  return cells;
} catch (NotFoundException e) {
  System.err.println("Failed to read from a non-existent table: " + e.getMessage());
  return null;
}

모든 테이블 행 검색

다음으로 전체 테이블을 검색합니다. Query 객체를 만들고 readRows() 메서드에 전달한 후 결과를 행 스트림에 할당합니다.

try {
  System.out.println("\nReading the entire table");
  Query query = Query.create(tableId);
  ServerStream<Row> rowStream = dataClient.readRows(query);
  List<Row> tableRows = new ArrayList<>();
  for (Row r : rowStream) {
    System.out.println("Row Key: " + r.getKey().toStringUtf8());
    tableRows.add(r);
    for (RowCell cell : r.getCells()) {
      System.out.printf(
          "Family: %s    Qualifier: %s    Value: %s%n",
          cell.getFamily(), cell.getQualifier().toStringUtf8(), cell.getValue().toStringUtf8());
    }
  }
  return tableRows;
} catch (NotFoundException e) {
  System.err.println("Failed to read a non-existent table: " + e.getMessage());
  return null;
}

테이블 삭제

마지막으로 deleteTable() 메서드로 테이블을 삭제합니다.

System.out.println("\nDeleting table: " + tableId);
try {
  adminClient.deleteTable(tableId);
  System.out.printf("Table %s deleted successfully%n", tableId);
} catch (NotFoundException e) {
  System.err.println("Failed to delete a non-existent table: " + e.getMessage());
}

하나로 결합

다음은 주석이 없는 전체 코드 샘플입니다.


package com.example.bigtable;

import static com.google.cloud.bigtable.data.v2.models.Filters.FILTERS;

import com.google.api.gax.rpc.NotFoundException;
import com.google.api.gax.rpc.ServerStream;
import com.google.cloud.bigtable.admin.v2.BigtableTableAdminClient;
import com.google.cloud.bigtable.admin.v2.BigtableTableAdminSettings;
import com.google.cloud.bigtable.admin.v2.models.CreateTableRequest;
import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.BigtableDataSettings;
import com.google.cloud.bigtable.data.v2.models.Filters.Filter;
import com.google.cloud.bigtable.data.v2.models.Query;
import com.google.cloud.bigtable.data.v2.models.Row;
import com.google.cloud.bigtable.data.v2.models.RowCell;
import com.google.cloud.bigtable.data.v2.models.RowMutation;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class HelloWorld {

  private static final String COLUMN_FAMILY = "cf1";
  private static final String COLUMN_QUALIFIER_GREETING = "greeting";
  private static final String COLUMN_QUALIFIER_NAME = "name";
  private static final String ROW_KEY_PREFIX = "rowKey";
  private final String tableId;
  private final BigtableDataClient dataClient;
  private final BigtableTableAdminClient adminClient;

  public static void main(String[] args) throws Exception {

    if (args.length != 2) {
      System.out.println("Missing required project id or instance id");
      return;
    }
    String projectId = args[0];
    String instanceId = args[1];

    HelloWorld helloWorld = new HelloWorld(projectId, instanceId, "test-table");
    helloWorld.run();
  }

  public HelloWorld(String projectId, String instanceId, String tableId) throws IOException {
    this.tableId = tableId;

    BigtableDataSettings settings =
        BigtableDataSettings.newBuilder().setProjectId(projectId).setInstanceId(instanceId).build();

    dataClient = BigtableDataClient.create(settings);

    BigtableTableAdminSettings adminSettings =
        BigtableTableAdminSettings.newBuilder()
            .setProjectId(projectId)
            .setInstanceId(instanceId)
            .build();

    adminClient = BigtableTableAdminClient.create(adminSettings);
  }

  public void run() throws Exception {
    createTable();
    writeToTable();
    readSingleRow();
    readSpecificCells();
    readTable();
    filterLimitCellsPerCol(tableId);
    deleteTable();
    close();
  }

  public void close() {
    dataClient.close();
    adminClient.close();
  }

  public void createTable() {
    if (!adminClient.exists(tableId)) {
      System.out.println("Creating table: " + tableId);
      CreateTableRequest createTableRequest =
          CreateTableRequest.of(tableId).addFamily(COLUMN_FAMILY);
      adminClient.createTable(createTableRequest);
      System.out.printf("Table %s created successfully%n", tableId);
    }
  }

  public void writeToTable() {
    try {
      System.out.println("\nWriting some greetings to the table");
      String[] names = {"World", "Bigtable", "Java"};
      for (int i = 0; i < names.length; i++) {
        String greeting = "Hello " + names[i] + "!";
        RowMutation rowMutation =
            RowMutation.create(tableId, ROW_KEY_PREFIX + i)
                .setCell(COLUMN_FAMILY, COLUMN_QUALIFIER_NAME, names[i])
                .setCell(COLUMN_FAMILY, COLUMN_QUALIFIER_GREETING, greeting);
        dataClient.mutateRow(rowMutation);
        System.out.println(greeting);
      }
    } catch (NotFoundException e) {
      System.err.println("Failed to write to non-existent table: " + e.getMessage());
    }
  }

  public Row readSingleRow() {
    try {
      System.out.println("\nReading a single row by row key");
      Row row = dataClient.readRow(tableId, ROW_KEY_PREFIX + 0);
      System.out.println("Row: " + row.getKey().toStringUtf8());
      for (RowCell cell : row.getCells()) {
        System.out.printf(
            "Family: %s    Qualifier: %s    Value: %s%n",
            cell.getFamily(), cell.getQualifier().toStringUtf8(), cell.getValue().toStringUtf8());
      }
      return row;
    } catch (NotFoundException e) {
      System.err.println("Failed to read from a non-existent table: " + e.getMessage());
      return null;
    }
  }

  public List<RowCell> readSpecificCells() {
    try {
      System.out.println("\nReading specific cells by family and qualifier");
      Row row = dataClient.readRow(tableId, ROW_KEY_PREFIX + 0);
      System.out.println("Row: " + row.getKey().toStringUtf8());
      List<RowCell> cells = row.getCells(COLUMN_FAMILY, COLUMN_QUALIFIER_NAME);
      for (RowCell cell : cells) {
        System.out.printf(
            "Family: %s    Qualifier: %s    Value: %s%n",
            cell.getFamily(), cell.getQualifier().toStringUtf8(), cell.getValue().toStringUtf8());
      }
      return cells;
    } catch (NotFoundException e) {
      System.err.println("Failed to read from a non-existent table: " + e.getMessage());
      return null;
    }
  }

  public List<Row> readTable() {
    try {
      System.out.println("\nReading the entire table");
      Query query = Query.create(tableId);
      ServerStream<Row> rowStream = dataClient.readRows(query);
      List<Row> tableRows = new ArrayList<>();
      for (Row r : rowStream) {
        System.out.println("Row Key: " + r.getKey().toStringUtf8());
        tableRows.add(r);
        for (RowCell cell : r.getCells()) {
          System.out.printf(
              "Family: %s    Qualifier: %s    Value: %s%n",
              cell.getFamily(), cell.getQualifier().toStringUtf8(), cell.getValue().toStringUtf8());
        }
      }
      return tableRows;
    } catch (NotFoundException e) {
      System.err.println("Failed to read a non-existent table: " + e.getMessage());
      return null;
    }
  }

  public void filterLimitCellsPerCol(String tableId) {
    Filter filter = FILTERS.limit().cellsPerColumn(1);
    readRowFilter(tableId, filter);
    readFilter(tableId, filter);
  }

  private void readRowFilter(String tableId, Filter filter) {
    String rowKey =
        Base64.getEncoder().encodeToString("greeting0".getBytes(StandardCharsets.UTF_8));
    Row row = dataClient.readRow(tableId, rowKey, filter);
    printRow(row);
    System.out.println("Row filter completed.");
  }

  private void readFilter(String tableId, Filter filter) {
    Query query = Query.create(tableId).filter(filter);
    ServerStream<Row> rows = dataClient.readRows(query);
    for (Row row : rows) {
      printRow(row);
    }
    System.out.println("Table filter completed.");
  }

  public void deleteTable() {
    System.out.println("\nDeleting table: " + tableId);
    try {
      adminClient.deleteTable(tableId);
      System.out.printf("Table %s deleted successfully%n", tableId);
    } catch (NotFoundException e) {
      System.err.println("Failed to delete a non-existent table: " + e.getMessage());
    }
  }

  private static void printRow(Row row) {
    if (row == null) {
      return;
    }
    System.out.printf("Reading data for %s%n", row.getKey().toStringUtf8());
    String colFamily = "";
    for (RowCell cell : row.getCells()) {
      if (!cell.getFamily().equals(colFamily)) {
        colFamily = cell.getFamily();
        System.out.printf("Column Family %s%n", colFamily);
      }
      String labels =
          cell.getLabels().size() == 0 ? "" : " [" + String.join(",", cell.getLabels()) + "]";
      System.out.printf(
          "\t%s: %s @%s%s%n",
          cell.getQualifier().toStringUtf8(),
          cell.getValue().toStringUtf8(),
          cell.getTimestamp(),
          labels);
    }
    System.out.println();
  }
}