最近更新时间:2023.06.09 13:41:30
首次发布时间:2022.12.27 16:12:46
表格数据库 HBase 版默认提供了 ZK 连接地址,同时也支持 Thrift 多语言访问,Thrift 是 HBase 标准版实例中的一种服务组件,基于 Apache Thrift(多语言支持的通信框架)开发。本文介绍基于 Python 程序通过 Thrift2 地址访问 HBase 实例的操作步骤。
python version
命令检查当前 Python 的版本。说明
表格数据库 HBase 版默认未开通 Thrift2 地址,您需要先申请 Thrift2 连接地址,申请方法,请参见申请 Thrift2 连接地址。
mv hbase/ /<ECS 实例或本地设备上 Python 的安装目录>/Python/3.8/lib/python/site-packages/
pip install thrift
# encoding:utf-8 #!/usr/bin/env python3 import random # 通过 TTransport、TSocket 和 TBinaryProtocol 开启一个 Thrift2 连接。 from thrift.transport import TTransport from thrift.transport import TSocket from thrift.protocol import TBinaryProtocol #来自thrift --gen py hbase.thrift from hbase import THBaseService from hbase.ttypes import TPut, TColumnValue, TGet def demo(): # 连接到 目标 HBase 实例 socket = TSocket.TSocket(<"HBase Thrift2 的连接地址">, 端口号>) socket.setTimeout(100) transport = TTransport.TFramedTransport(socket) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = THBaseService.Client(protocol) transport.open() # 生成一个随机 Key 作为一行记录的唯一标识、 # 本文示例中 Key 名称为 examplexxxx,其中 example 为名称中的常量,xxxx 为变量,该变量是由一个 1~1000 的数字转换成的字符串。 key = "example" + str(random.randint(1,1000)) # 使用 TPut 命令往 Key 中传入数据。 # Key 名称、列簇名(family)、列名(qualifier)以及 value 值都需要通过 b 符号转化为 bytes 类型。 tput = TPut( row=str.encode(key), columnValues=[ TColumnValue(family=b'f1', qualifier=b'c1', value=b'0.28'), ] ) client.put(b't1', tput) #通过 TGet 命令获取 Key 中的数据。 tget = TGet(row=str.encode(key)) tresult = client.get(b't1', tget) for col in tresult.columnValues: print(col.qualifier, '=', col.value) # 通过 close() 函数关闭 Thrift2 连接。 transport.close() socket.close() if __name__ == "__main__": demo()