最近在服务器上安装了hbase数据库,然后尝试着用python3去查询数据库的信息以及各表格的占用空间,总结如下:
hbase是使用java语言写的,所以hbase原生支持java,同时也对于别的语言提供了thrift接口,通过thrift接口我们可以通过python(还支持其他语言)去对数据库进行处理。所以我们需要在服务器端安装thrift,本文安装的版本为0.11.0,安装使用thrift参考链接如下:
用Python3.6操作HBase之HBase-Thrift:https://blog.csdn.net/luanpeng825485697/article/details/81048468
首先说下我的Linux环境:
jdk:1.8
zookeeper:3.4.14
hadoop:2.7.6
hbase:1.2.6
接着说下我的python环境:
thrift:0.11.0
hbase-thrift:0.20.4 (hbase包对python3兼容有点问题,需要根据上面链接中的方法替换两个文件)
pyhdfs:0.2.2
环境搭建完成后,我们需在在服务端开启服务,依次开启:
zookeeper
hadoop
hbase
thrift
建立python项目,项目结构如下:
+pythonProject
-conf.config
-main.py
在conf.config中主要是写入了服务器的ip以及端口号信息,hbase的thrift服务一般提供了9090端口,hadoop服务提供了50070端口,userName是服务器上的用户名:
[hbase]
host = 192.168.11.1
port = 9090
[hdfs]
port = 50070
userName = hadoop
在main.py文件中,主要通过hbase包去实现获取表格的域名空间名称以及表格名称,通过pyhdfs包去获取表格的占用空间。
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol
from hbase import Hbase
import pyhdfs
import configparser
def getConfig(): # 获取conf.config文件中的服务器ip以及各端口信息
configDict = {}
conf = configparser.ConfigParser()
conf.read('conf.config')
# hbase config
hbaseHost = conf.get('hbase', 'host')
hbasePort = conf.get('hbase', 'port')
configDict['hbaseHosts'] = hbaseHost
configDict['hbasePort'] = hbasePort
# hdfs config
hdfsHost = hbaseHost
hdfsPort = conf.get('hdfs', 'port')
hdfsUser = conf.get('hdfs', 'userName')
configDict['hdfsHosts'] = hdfsHost + ',' + hdfsPort
configDict['hdfsUser'] = hdfsUser
return configDict
def countTableSize(tableName, hdfsClient): # 获取对应表格的内存占用大小
tablePath = '/hbase/data/' + tableName[0] + '/' + tableName[1]
flag = hdfsClient.exists(tablePath) # 查询文件是否存在
if flag is True:
tableSize = hdfsClient.get_content_summary(tablePath).spaceConsumed
else:
tableSize = 0
return tableSize
def countTable(tablesName, configDict): # 统计各表格的命名空间,名称以及大小
# connect hdfs
client = pyhdfs.HdfsClient(hosts=configDict['hdfsHosts'], user_name=configDict['hdfsUser'])
# create table list
tableList = []
for table in tablesName:
tableT = table.split(':')
if len(tableT) == 2: # 当有命名空间时
pass
else: # 当没有命名空间时,默认为default
tableT = ['default', table[0]]
tableSize = countTableSize(tableT, client)
tableList.append({'namespace': tableT[0], 'tablename': tableT[1], 'size': tableSize})
return tableList
if __name__ == "__main__":
configDict = getConfig()
# connect to hbase
socket = TSocket.TSocket(configDict['hbaseHosts'], int(configDict['hbasePort']))
socket.setTimeout(5000)
transport = TTransport.TBufferedTransport(socket)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Hbase.Client(protocol)
socket.open()
tablesName = client.getTableNames()
tableList = countTable(tablesName, configDict)
print(tableList)