示例:Java 版“Hello world”应用

本代码示例是一个通过 Java 版 Cloud Bigtable 客户端库,使用 Java 编写的“hello world”应用。该示例说明如何完成以下任务:

  • 连接到 Cloud Bigtable 实例。
  • 新建一个表。
  • 将数据写入表中。
  • 重新读取这些数据。
  • 删除表。

运行示例

本代码使用 Java 版 Google Cloud 客户端库中的 Google Cloud Bigtable 库与 Cloud Bigtable 通信。

在开始之前,请先按照 GitHub 上的 Google Cloud Platform 示例说明操作。

将 Cloud 客户端库用于 Cloud Bigtable

本示例应用将连接到 Cloud Bigtable 并演示一些简单操作。

连接到 Cloud Bigtable

如需开始连接,您需要一个用来与数据 API 客户端库通信的数据客户端,以及一个用来与管理员 API 客户端库通信的表管理员客户端。

首先,实例化一个 BigtableDataSettings 对象,其中包含 hello world 应用要使用的项目 ID 和实例 ID。然后将设置传递给 BigtableDataClient.create() 方法以便创建数据客户端。

对管理员客户端执行类似操作,即首先通过创建 BigtableTableAdminSettings 对象建立设置,然后使用该设置创建 BigtableTableAdminClient 对象。

最佳做法是务必在使用 Cloud 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[] greetings = {"Hello World!", "Hello Bigtable!", "Hello Java!"};
  for (int i = 0; i < greetings.length; i++) {
    RowMutation rowMutation =
        RowMutation.create(tableId, ROW_KEY_PREFIX + i)
            .setCell(COLUMN_FAMILY, COLUMN_QUALIFIER, greetings[i]);
    dataClient.mutateRow(rowMutation);
    System.out.println(greetings[i]);
  }
} catch (NotFoundException e) {
  System.err.println("Failed to write to non-existent table: " + e.getMessage());
}

按行键读取行

使用数据客户端的 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());
  }
} catch (NotFoundException e) {
  System.err.println("Failed to read from a non-existent table: " + e.getMessage());
}

扫描所有表行

接下来,扫描整个表。创建一个 Query 对象,将其传递给 readRows() 方法,然后将结果分配给行信息流。

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

删除表

最后,使用 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.m.examples.bigtable;

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.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;

public class HelloWorld {

  private static final String COLUMN_FAMILY = "cf1";
  private static final String COLUMN_QUALIFIER = "greeting";
  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();
    readTable();
    deleteTable();
    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[] greetings = {"Hello World!", "Hello Bigtable!", "Hello Java!"};
      for (int i = 0; i < greetings.length; i++) {
        RowMutation rowMutation =
            RowMutation.create(tableId, ROW_KEY_PREFIX + i)
                .setCell(COLUMN_FAMILY, COLUMN_QUALIFIER, greetings[i]);
        dataClient.mutateRow(rowMutation);
        System.out.println(greetings[i]);
      }
    } catch (NotFoundException e) {
      System.err.println("Failed to write to non-existent table: " + e.getMessage());
    }
  }

  public void 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());
      }
    } catch (NotFoundException e) {
      System.err.println("Failed to read from a non-existent table: " + e.getMessage());
    }
  }

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

  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());
    }
  }
}