範例:Java App Engine 彈性環境

本範例為一以 Java 語言撰寫的 App Engine 應用程式,把一些「hello world」問候語寫入功能表,再把它們讀回。本應用程式使用 App Engine 執行環境,對於 App Engine API 有完整的存取權限。可在雲端的 App Engine 彈性環境 下執行。這個應用程式的程式碼位於 GitHub 存放區 GoogleCloudPlatform/cloud-bigtable-examplesjava/gae-flexible-helloworld 目錄中。

程式碼範例綜覽

程式碼範例包括以下類別︰

BigtableHelper

BigtableHelper 提供一個方法,與 Cloud Bigtable 建立連線。此也會把連線相關訊息儲存於快取區,已儲存的連線如果存在,也提供一方法將其取回。這是因為建立連線是相當高成本的操作。

public static void connect() throws IOException {

  if (PROJECT_ID == null || INSTANCE_ID == null ) {
    if (sc != null) {
      sc.log("environment variables BIGTABLE_PROJECT, and BIGTABLE_INSTANCE need to be defined.");
    }
    return;
  }

  connection = BigtableConfiguration.connect(PROJECT_ID, INSTANCE_ID);
}

public static Connection getConnection() {
  if (connection == null) {
    try {
      connect();
    } catch (IOException e) {
      if (sc != null) {
        sc.log("connect ", e);
      }
    }
  }
  if (connection == null) {
    if (sc != null) {
      sc.log("BigtableHelper-No Connection");
    }
  }
  return connection;
}

BigtableHelloWorld

BigtableHelloWorld 是用來將一系列的問候語寫入 Cloud Bigtable,然後把它們讀回並顯示。此類別從 BigtableHelper 獲得 Cloud Bigtable 連線;使用該連線得到一 Table 物件,讓您可以讀取和寫入值;並使用 Table 物件將資料寫入資料表,或從資料表讀取:

/**
 * A minimal application that connects to Cloud Bigtable using the native HBase API
 * and performs some basic operations.
 */
public class BigtableHelloWorld {

  // Refer to table metadata names by byte array in the HBase API
  private static final byte[] TABLE_NAME = Bytes.toBytes("Hello-Bigtable");
  private static final byte[] COLUMN_FAMILY_NAME = Bytes.toBytes("cf1");
  private static final byte[] COLUMN_NAME = Bytes.toBytes("greeting");

  // Write some friendly greetings to Cloud Bigtable
  private static final String[] GREETINGS =
      { "Hello World!", "Hello Cloud Bigtable!", "Hello HBase!" };

  public static String create(Connection connection) {
    try {
        // The admin API lets us create, manage and delete tables
      Admin admin = connection.getAdmin();

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

      admin.createTable(descriptor);
    } catch (IOException e) {
      return "Table exists.";
    }
    return "Create table " + Bytes.toString(TABLE_NAME);
  }

  /**
   * Connects to Cloud Bigtable, runs some basic operations and prints the results.
   */
  public static String doHelloWorld() {

    StringBuilder result = new StringBuilder();

    // Create the Bigtable connection, use try-with-resources to make sure it gets closed
    Connection connection = BigtableHelper.getConnection();
    result.append(create(connection));
    result.append("<br><br>");
    try (Table table = connection.getTable(TableName.valueOf(TABLE_NAME))) {

      // Retrieve the table we just created so we can do some reads and writes

      // Write some rows to the table
      result.append("Write some greetings to the table<br>");
      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));
      result.append("Get a single greeting by row key<br>");
      result.append("     ");
      result.append(rowKey);
      result.append("= ");
      result.append(greeting);
      result.append("<br>");

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

      result.append("Scan for all greetings:");
      ResultScanner scanner = table.getScanner(scan);
      for (Result row : scanner) {
        byte[] valueBytes = row.getValue(COLUMN_FAMILY_NAME, COLUMN_NAME);
        result.append("    ");
        result.append(Bytes.toString(valueBytes));
        result.append("<br>");
      }

    } catch (IOException e) {
      result.append("Exception while running HelloWorld: " + e.getMessage() + "<br>");
      result.append(e.toString());
      return result.toString();
    }

    return result.toString();
  }

}
本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Bigtable 說明文件