| // HBase thrift2 C++编程示例 #include "THBaseService.h" #include // PRIu64 #include #include #include // 请注意客户端使用的thrift的Transport和Protocol要和hbase thrift2服务端保持一致, // 否则调用时,可能总是报超时,或其它错误!!! // // 运行之前,请通过HBase shell创建好表:create 'test','cf1','cf2' // 或指定版本数:create 'test',{NAME=>'cf1',VERSIONS=>2},{NAME=>'cf2',VERSIONS=>3} // 删除表,按顺序执行以下两条HBase shell命令: // disable 'test' // drop 'test' STRING_ARG_DEFINE(hbase_ip, "192.168.0.1", "hbase thrift ip"); INTEGER_ARG_DEFINE(uint16_t, hbase_port, 9090, 1000, 50000, "hbase thrift port"); int main(int argc, char* argv[]) { std::string errmsg; if (!mooon::utils::parse_arguments(argc, argv, &errmsg)) { fprintf(stderr, "parameter error: %s\n", errmsg.c_str()); exit(1); } using namespace apache; using namespace apache::hadoop; std::string hbase_ip = mooon::argument::hbase_ip->value(); uint16_t hbase_port = mooon::argument::hbase_port->value(); mooon::net::CThriftClientHelper hbase_client(hbase_ip, hbase_port); try { hbase_client.connect(); // 连接hbase thrift2 server fprintf(stdout, "connect %s:%d ok\n", hbase_ip.c_str(), hbase_port); std::string tablename = "test"; // 表名,确保运行之前已创建好 std::string rowkey = "row1"; // 行Key std::string family = "cf1"; // 例族名 std::string columnname = "f1"; // 例名 std::string columnvalue = "value1"; // 例值 // 插入参数设置 std::vector columns_value(1); columns_value[0].__set_family(family); columns_value[0].__set_qualifier(columnname); columns_value[0].__set_value(columnvalue); hbase::thrift2::TPut put; put.__set_row(rowkey); put.__set_columnValues(columns_value); hbase_client->put(tablename, put); // 插入,出错抛异常hbase::thrift2::TIOError // 查询参数设置 hbase::thrift2::TGet input; input.__set_row(rowkey); hbase::thrift2::TResult result; // 查询结果存放在这里 hbase_client->get(result, tablename, input); // 查询,出错抛异常hbase::thrift2::TIOError // 显示查询结果 for (int i=0; i { const hbase::thrift2::TColumnValue& column_value_ref = result.columnValues[i]; fprintf(stdout, "family[%s]/qualifier[%s]/timestamp[%"PRIu64"]: %s\n", column_value_ref.family.c_str(), column_value_ref.qualifier.c_str(), column_value_ref.timestamp, column_value_ref.value.c_str()); } } catch (hbase::thrift2::TIOError& ex) { fprintf(stderr, "IOError: %s\n", ex.what()); } catch (apache::thrift::transport::TTransportException& ex) { // 如果和服务端的Transport和Protocol不同,这里的错误是“EAGAIN (timed out)” fprintf(stderr, "(%d)%s\n", ex.getType(), ex.what()); } catch (apache::thrift::TApplicationException& ex) { fprintf(stderr, "%s\n", ex.what()); } catch (thrift::TException& ex) { fprintf(stderr, "%s\n", ex.what()); } return 0; } |