‫HBase APIs for Java hello world

בדוגמה הזו מוצגת אפליקציית hello world שמשתמשת בספריית הלקוח Bigtable HBase ל-Java, כדי להמחיש איך:

  • מגדירים אימות
  • מתחברים למכונה של Bigtable.
  • ליצור טבלה חדשה.
  • כתיבת נתונים בטבלה.
  • קוראים את הנתונים בחזרה.
  • מוחקים את הטבלה.

מגדירים אימות

כדי להשתמש בדוגמאות של Java שבדף הזה בסביבת פיתוח מקומית, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

  1. התקינו את ה-CLI של Google Cloud.

  2. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  3. אם אתם משתמשים במעטפת מקומית, אתם צריכים ליצור פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הרצת הדוגמה

בדוגמה נעשה שימוש בממשקי ה-API של HBase כדי לתקשר עם Bigtable. הקוד של הדוגמה הזו נמצא במאגר GitHub‏ GoogleCloudPlatform/cloud-bigtable-examples, בספרייה java/hello-world.

כדי להריץ את תוכנית הדוגמה הזו, פועלים לפי ההוראות לדוגמה ב-GitHub.

שימוש בממשקי ה-API של HBase

אפליקציית הדוגמה מתחברת ל-Bigtable ומדגימה כמה פעולות פשוטות.

התקנה וייבוא של ספריית הלקוח

בדוגמה הזו נעשה שימוש ב-Bigtable HBase client for Java, וגם ב-Maven. הוראות לשימוש בספריית הלקוח

בדוגמה נעשה שימוש בהצהרות הייבוא הבאות:

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

התחברות ל-Bigtable

מתחברים ל-Bigtable באמצעות המחלקה BigtableConfiguration.

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