Java hello world
這個程式碼範例是以 Java 撰寫的「Hello World」應用程式,使用 Java 適用的 Bigtable 用戶端程式庫,為您說明如何完成下列工作:
- 設定驗證方法
- 連線至 Bigtable 執行個體。
- 建立新的資料表。
- 將資料寫入資料表。
- 讀取資料。
- 刪除資料表。
執行範例
這段程式碼使用 Google Cloud Java 適用的用戶端程式庫中的 Bigtable 用戶端程式庫,與 Bigtable 進行通訊。
開始之前,請按照參考文件中的設定步驟操作。
搭配 Bigtable 使用 Cloud 用戶端程式庫
這個應用程式範例會連線至 Bigtable,示範部分基本作業。
連線至 Bigtable
如要開始連結,您必須使用資料用戶端與 Data API 用戶端程式庫通訊,以及必須使用資料表管理用戶端與 Admin API 用戶端程式庫通訊。
首先,請例項化 BigtableDataSettings
物件,其中包含 hello world
應用程式將使用的專案 ID 和執行個體 ID。然後將設定傳送到 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.of(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());
}
依資料列索引鍵讀取資料列
使用資料用戶端的 readRow()
方法讀取您寫入的第一個資料列。
try {
System.out.println("\nReading a single row by row key");
Row row = dataClient.readRow(TableId.of(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.of(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.of(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 com.google.cloud.bigtable.data.v2.models.TableId;
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.of(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.of(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.of(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.of(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.of(tableId), rowKey, filter);
printRow(row);
System.out.println("Row filter completed.");
}
private void readFilter(String tableId, Filter filter) {
Query query = Query.create(TableId.of(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();
}
}