python通过thrift连接hbase

安装thrift

pip install thrift

编译thrift hbase idl文件

thrift提供了两个版本的idl文件:https://github.com/apache/hbase/tree/master/hbase-thrift/src/main/resources/org/apache/hadoop/hbase

首先,thrift2 模仿了 HBase Java API 的数据类型和方法定义,调用方式更人性化一些。比如,构建一个 Get 操作的 Java 代码是:

Get get = new Get(Bytes.toBytes("rowkey"));
get.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("col1"));
get.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("col2"));

在 thrift2 中有对应的 TGet 类型:

tget = TGet(
    row='rowkey',
    columns=[
        TColumn(family='cf', qualifier='col1'),
        TColumn(family='cf', qualifier='col2'),
    ]
)

如果使用旧版的 thrift,我们就需要直接调用其众多的 get 方法之一了:

client.getRowWithColumns(
    tableName='tbl',
    row='rowkey',
    columns=['cf:col1', 'cf:col2'],
    attributes=None
)

第二个不同点在于 thrift2 目前尚缺少 HBase 管理相关的接口,如 createTable、majorCompact 等。这些 API 仍在开发过程中,因此如果你需要通过 Thrift 来建表或维护 HBase,就只能使用旧版的 thrift 了。

决定了使用哪个版本的描述文件后,我们就可以将 hbase.thrift 下载到本地,通过它来生成 Python 代码。

thrift -gen py hbase.thrift

生产结果文件夹gen-py,内容如下:

gen-py/hbase/__init__.py
gen-py/hbase/constants.py
gen-py/hbase/THBaseService.py
gen-py/hbase/ttypes.py

cp里面文件到指定python安装目录site-packages里

cp -R hbase /usr/lib/python2.7/site-packages/

查询数据

thrift

from thrift import Thrift
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol
from hbase import Hbase

#server端地址和端口,web是HMaster也就是thriftServer主机名,9090是thriftServer默认端口
transport = TSocket.TSocket('web', 9090)
#可以设置超时
transport.setTimeout(5000)
#设置传输方式(TFramedTransport或TBufferedTransport)
trans = TTransport.TBufferedTransport(transport)
#设置传输协议
protocol = TBinaryProtocol.TBinaryProtocol(trans)
#确定客户端
client = Hbase.Client(protocol)
#打开连接
transport.open()

from hbase.ttypes import ColumnDescriptor, Mutation, BatchMutation, TRegionInfo
from hbase.ttypes import IOError, AlreadyExists

#获取表名
client.getTableNames()

#api说明https://blog.csdn.net/y472360651/article/details/79055875

thrift2

from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
from thrift.transport import TTransport
from hbase import THBaseService

transport = TTransport.TBufferedTransport(TSocket.TSocket('127.0.0.1', 9090))
protocol = TBinaryProtocol.TBinaryProtocolAccelerated(transport)
client = THBaseService.Client(protocol)
transport.open()
# 使用 client 实例进行操作
from hbase.ttypes import TPut, TColumnValue, TGet
tput = TPut(
    row='sys.cpu.user:20180421:192.168.1.1',
    columnValues=[
        TColumnValue(family='cf', qualifier='1015', value='0.28'),
    ]
)
client.put('tsdata', tput)

tget = TGet(row='sys.cpu.user:20180421:192.168.1.1')
tresult = client.get('tsdata', tget)
for col in tresult.columnValues:
    print(col.qualifier, '=', col.value)
transport.close()

#api说明https://blog.csdn.net/zjerryj/article/details/80045657
04-10 08:40