BigtableHelper fournit une méthode pour créer une connexion à Bigtable. Il met également en cache la connexion et fournit une méthode permettant de récupérer la connexion en cache si elle existe. La création d'une connexion est une opération relativement coûteuse. Il est donc recommandé de toujours créer une connexion unique et de la réutiliser.
publicstaticvoidconnect()throwsIOException{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);}/** * Get the shared connection to Cloud Bigtable. * * @return the connection */publicstaticConnectiongetConnection(){if(connection==null){try{connect();}catch(IOExceptione){if(sc!=null){sc.log("connect ",e);}}}if(connection==null){if(sc!=null){sc.log("BigtableHelper-No Connection");}}returnconnection;}
BigtableHelloWorld
BigtableHelloWorld permet d'écrire une série de messages dans Bigtable, puis de les relire et de les afficher. La classe obtient une connexion Bigtable depuis BigtableHelper, utilise la connexion pour obtenir un objet Table qui vous permet de lire et d'écrire des valeurs, puis utilise l'objet Table pour lire et écrire dans la table.
/** * A minimal application that connects to Cloud Bigtable using the native HBase API and performs * some basic operations. */publicclassBigtableHelloWorld{// Refer to table metadata names by byte array in the HBase APIprivatestaticfinalbyte[]TABLE_NAME=Bytes.toBytes("Hello-Bigtable");privatestaticfinalbyte[]COLUMN_FAMILY_NAME=Bytes.toBytes("cf1");privatestaticfinalbyte[]COLUMN_NAME=Bytes.toBytes("greeting");// Write some friendly greetings to Cloud BigtableprivatestaticfinalString[]GREETINGS={"Hello World!","Hello Cloud Bigtable!","Hello HBase!"};/** * Create a table -- first time only. * * @param connection to Bigtable * @return the status */publicstaticStringcreate(Connectionconnection){try{// The admin API lets us create, manage and delete tablesAdminadmin=connection.getAdmin();// Create a table with a single column familyHTableDescriptordescriptor=newHTableDescriptor(TableName.valueOf(TABLE_NAME));descriptor.addFamily(newHColumnDescriptor(COLUMN_FAMILY_NAME));admin.createTable(descriptor);}catch(IOExceptione){return"Table exists.";}return"Create table "+Bytes.toString(TABLE_NAME);}/** Connects to Cloud Bigtable, runs some basic operations and prints the results. */publicstaticStringdoHelloWorld(){StringBuilderresult=newStringBuilder();// Create the Bigtable connection, use try-with-resources to make sure it gets closedConnectionconnection=BigtableHelper.getConnection();result.append(create(connection));result.append("<br><br>");try(Tabletable=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 tableresult.append("Write some greetings to the table<br>");for(inti=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-designStringrowKey="greeting"+i;// Put a single row into the table. We could also pass a list of Puts to write a batch.Putput=newPut(Bytes.toBytes(rowKey));put.addColumn(COLUMN_FAMILY_NAME,COLUMN_NAME,Bytes.toBytes(GREETINGS[i]));table.put(put);}// Get the first greeting by row keyStringrowKey="greeting0";ResultgetResult=table.get(newGet(Bytes.toBytes(rowKey)));Stringgreeting=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.Scanscan=newScan();result.append("Scan for all greetings:");ResultScannerscanner=table.getScanner(scan);for(Resultrow:scanner){byte[]valueBytes=row.getValue(COLUMN_FAMILY_NAME,COLUMN_NAME);result.append(" ");result.append(Bytes.toString(valueBytes));result.append("<br>");}}catch(IOExceptione){result.append("Exception while running HelloWorld: "+e.getMessage()+"<br>");result.append(e.toString());returnresult.toString();}returnresult.toString();}}
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[[["\u003cp\u003eThis Java application demonstrates how to interact with a Bigtable database from the Google App Engine standard environment using the Java 8 runtime.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eBigtableHelper\u003c/code\u003e class manages the connection to Bigtable, caching it for reuse to improve performance.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eBigtableHelloWorld\u003c/code\u003e class handles writing greetings to a Bigtable table, reading them back, and displaying them.\u003c/p\u003e\n"],["\u003cp\u003eThe code utilizes the HBase API to create a table, write rows with column family, and scan/read the values from the table.\u003c/p\u003e\n"],["\u003cp\u003eThe example is intended to showcase the basic operations with Bigtable, and recommends referring to the documentation on schema-design for better performance in production applications.\u003c/p\u003e\n"]]],[],null,["Example: Java App Engine standard environment\n\nThis example is an [App Engine](/appengine) application, written in\nJava, that writes some \"hello world\" greetings to a Bigtable\ntable and reads them back. The application runs on Google Cloud in the\nApp Engine [standard environment](/appengine/docs/standard). The application\nuses the [Java 8 runtime](/appengine/docs/standard/java/runtime-java8). The code for this application is in the GitHub\nrepository [GoogleCloudPlatform/java-docs-samples](https://github.com/GoogleCloudPlatform/java-docs-samples), in the\ndirectory `appengine-java8/bigtable`.\n\nOverview of the code sample\n\nThe code sample includes the following classes:\n\n- [`BigtableHelper`](https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/appengine-java8/bigtable/src/main/java/com/example/bigtable/BigtableHelper.java), which provides a connection to Bigtable.\n- [`BigtableHelloWorld`](https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/appengine-java8/bigtable/src/main/java/com/example/bigtable/BigtableHelloWorld.java), which writes to and reads from Bigtable.\n\nBigtableHelper\n\n`BigtableHelper` provides a method to create a connection to\nBigtable. It also caches the connection and provides a method that\nwill retrieve the cached connection if it exists. Creating a connection is a\nrelatively expensive operation, so as a best practice you should always create a\nsingle connection and reuse it. \n\n public static void connect() throws IOException {\n\n if (PROJECT_ID == null || INSTANCE_ID == null) {\n if (sc != null) {\n sc.log(\"environment variables BIGTABLE_PROJECT, and BIGTABLE_INSTANCE need to be defined.\");\n }\n return;\n }\n\n connection = BigtableConfiguration.connect(PROJECT_ID, INSTANCE_ID);\n }\n\n /**\n * Get the shared connection to Cloud Bigtable.\n *\n * @return the connection\n */\n public static Connection getConnection() {\n if (connection == null) {\n try {\n connect();\n } catch (IOException e) {\n if (sc != null) {\n sc.log(\"connect \", e);\n }\n }\n }\n if (connection == null) {\n if (sc != null) {\n sc.log(\"BigtableHelper-No Connection\");\n }\n }\n return connection;\n }\n\nBigtableHelloWorld\n\n`BigtableHelloWorld` is used to write a series of greetings to\nBigtable, read the greetings, and then display them. The class\ngets a Bigtable connection from `BigtableHelper`, uses the\nconnection to get a `Table` object, which lets you to read and write values,\nthen uses the `Table` object to write to and read from the table. \n\n\n /**\n * A minimal application that connects to Cloud Bigtable using the native HBase API and performs\n * some basic operations.\n */\n public class BigtableHelloWorld {\n\n // Refer to table metadata names by byte array in the HBase API\n private static final byte[] TABLE_NAME = Bytes.toBytes(\"Hello-Bigtable\");\n private static final byte[] COLUMN_FAMILY_NAME = Bytes.toBytes(\"cf1\");\n private static final byte[] COLUMN_NAME = Bytes.toBytes(\"greeting\");\n\n // Write some friendly greetings to Cloud Bigtable\n private static final String[] GREETINGS = {\n \"Hello World!\", \"Hello Cloud Bigtable!\", \"Hello HBase!\"\n };\n\n /**\n * Create a table -- first time only.\n *\n * @param connection to Bigtable\n * @return the status\n */\n public static String create(Connection connection) {\n try {\n // The admin API lets us create, manage and delete tables\n Admin admin = connection.getAdmin();\n\n // Create a table with a single column family\n HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(TABLE_NAME));\n descriptor.addFamily(new HColumnDescriptor(COLUMN_FAMILY_NAME));\n\n admin.createTable(descriptor);\n } catch (IOException e) {\n return \"Table exists.\";\n }\n return \"Create table \" + Bytes.toString(TABLE_NAME);\n }\n\n /** Connects to Cloud Bigtable, runs some basic operations and prints the results. */\n public static String doHelloWorld() {\n\n StringBuilder result = new StringBuilder();\n\n // Create the Bigtable connection, use try-with-resources to make sure it gets closed\n Connection connection = BigtableHelper.getConnection();\n result.append(create(connection));\n result.append(\"\u003cbr\u003e\u003cbr\u003e\");\n try (Table table = connection.getTable(TableName.valueOf(TABLE_NAME))) {\n\n // Retrieve the table we just created so we can do some reads and writes\n\n // Write some rows to the table\n result.append(\"Write some greetings to the table\u003cbr\u003e\");\n for (int i = 0; i \u003c GREETINGS.length; i++) {\n // Each row has a unique row key.\n //\n // Note: This example uses sequential numeric IDs for simplicity, but\n // this can result in poor performance in a production application.\n // Since rows are stored in sorted order by key, sequential keys can\n // result in poor distribution of operations across nodes.\n //\n // For more information about how to design a Bigtable schema for the\n // best performance, see the documentation:\n //\n // https://cloud.google.com/bigtable/docs/schema-design\n String rowKey = \"greeting\" + i;\n\n // Put a single row into the table. We could also pass a list of Puts to write a batch.\n Put put = new Put(Bytes.toBytes(rowKey));\n put.addColumn(COLUMN_FAMILY_NAME, COLUMN_NAME, Bytes.toBytes(GREETINGS[i]));\n table.put(put);\n }\n\n // Get the first greeting by row key\n String rowKey = \"greeting0\";\n Result getResult = table.get(new Get(Bytes.toBytes(rowKey)));\n String greeting = Bytes.toString(getResult.getValue(COLUMN_FAMILY_NAME, COLUMN_NAME));\n result.append(\"Get a single greeting by row key\u003cbr\u003e\");\n\n result.append(\" \");\n result.append(rowKey);\n result.append(\"= \");\n result.append(greeting);\n result.append(\"\u003cbr\u003e\");\n\n // Now scan across all rows.\n Scan scan = new Scan();\n\n result.append(\"Scan for all greetings:\");\n ResultScanner scanner = table.getScanner(scan);\n for (Result row : scanner) {\n byte[] valueBytes = row.getValue(COLUMN_FAMILY_NAME, COLUMN_NAME);\n result.append(\" \");\n result.append(Bytes.toString(valueBytes));\n result.append(\"\u003cbr\u003e\");\n }\n\n } catch (IOException e) {\n result.append(\"Exception while running HelloWorld: \" + e.getMessage() + \"\u003cbr\u003e\");\n result.append(e.toString());\n return result.toString();\n }\n\n return result.toString();\n }\n }"]]