C++ 版 Hello World
本示例是一个简单的“hello world”应用,采用 C++ 编写而成,旨在说明如何完成以下操作:
- 设置身份验证
- 连接到 Bigtable 实例。
- 新建一个表。
- 将数据写入表中。
- 重新读取这些数据。
- 删除表。
设置身份验证
如需在本地开发环境中使用本页面上的 C++ 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
如需了解详情,请参阅 Set up authentication for a local development environment。
运行示例
此示例使用 Google Cloud C++ 版客户端库的 Cloud Bigtable 软件包与 Bigtable 通信。
要运行此示例程序,请按照 GitHub 上的说明操作。
将 Google Cloud 客户端库与 Bigtable 搭配使用
示例应用会连接到 Bigtable 并演示一些简单操作。
安装和导入客户端库
从 GitHub 中下载或克隆 Bigtable C++ 客户端库,然后对其进行编译。按照顶层 README 中的编译器说明进行操作。
添加必需的标头。
连接到 Bigtable
使用 MakeBigtableTableAdminConnection()
构建 BigtableTableAdminClient
,用于创建表。
创建表
为包含一个列族的表定义架构。为列族设置垃圾回收规则,使每个值的版本不超过一个版本。通过此架构使用 BigtableTableAdminClient::CreateTable()
对表对象进行实例化。然后创建一个数据客户端,可用于将数据移入和移出表。
将行写入表
循环遍历一系列问候语字符串,从而为该表创建一些新行。
在每次迭代中,使用 SingleRowMutation
来定义行并为其分配行键和值。然后调用 Table::Apply()
,将变更应用于该行。
创建过滤条件
在读取您写入的数据之前,请使用 Filter::ColumnRangeClosed()
创建过滤条件,以限制 Bigtable 返回的数据。此过滤条件指示 Bigtable 仅返回每个值的最新版本,即使表中包含已过期但尚未被垃圾回收移除的单元。
按行键读取行
调用 Table::ReadRow()
函数,传入行键和过滤条件,以获取该行中每个值的一个版本。
扫描所有表行
使用 Table::ReadRows()
从表中读取一系列行。
删除表
使用 BigtableTableAdminClient::DeleteTable()
删除表格。
综合应用
以下为不包含注释的完整示例。