python经过thrift链接hbasepython
pip install thrift
thrift提供了两个版本的idl文件:https://github.com/apache/hbase/tree/master/hbase-thrift/src/main/resources/org/apache/hadoop/hbasegit
首先,thrift2 模仿了 HBase Java API 的数据类型和方法定义,调用方式更人性化一些。好比,构建一个 Get 操做的 Java 代码是:github
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 类型:web
tget = TGet( row='rowkey', columns=[ TColumn(family='cf', qualifier='col1'), TColumn(family='cf', qualifier='col2'), ] )
若是使用旧版的 thrift,咱们就须要直接调用其众多的 get 方法之一了:apache
client.getRowWithColumns( tableName='tbl', row='rowkey', columns=['cf:col1', 'cf:col2'], attributes=None )
第二个不一样点在于 thrift2 目前尚缺乏 HBase 管理相关的接口,如 createTable、majorCompact 等。这些 API 仍在开发过程当中,所以若是你须要经过 Thrift 来建表或维护 HBase,就只能使用旧版的 thrift 了。api
决定了使用哪一个版本的描述文件后,咱们就能够将 hbase.thrift 下载到本地,经过它来生成 Python 代码。python2.7
thrift -gen py hbase.thrift
生产结果文件夹gen-py,内容以下:oop
gen-py/hbase/__init__.py gen-py/hbase/constants.py gen-py/hbase/THBaseService.py gen-py/hbase/ttypes.py
cp里面文件到指定python安装目录site-packages里spa
cp -R hbase /usr/lib/python2.7/site-packages/
thrift.net
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