适用于 Java 版 Hello World 的 API HBase

本示例是一个使用 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 并演示一些简单操作。

安装和导入客户端库

此示例使用适用于 Java 的 Bigtable HBase 客户端和 Maven。请参阅使用该客户端库的说明

此示例使用了以下导入:

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