Python中如何使用thrift操作Hbase并解决验证问题

由于项目需要,我需要读写 Hbase,然后我就用 Python 做了,但是 thrifr api 根本没有设置用户密码的地方, https://wiki.apache.org/hadoop/Hbase/ThriftApi

而且 Hbase 要开放 thrifr 服务,那会很不安全吧
Python中如何使用thrift操作Hbase并解决验证问题

3 回复

要使用Python通过Thrift操作HBase,你需要安装happybase或直接使用thrift生成客户端。这里以happybase为例,因为它封装得更好用。

首先,安装happybase:

pip install happybase

然后,确保HBase的Thrift服务已经启动(默认端口9090)。连接时如果遇到验证问题,通常需要正确设置transport和protocol。以下是完整示例:

import happybase

def connect_hbase(host='localhost', port=9090, timeout=5000):
    """
    连接HBase Thrift服务
    :param host: HBase Thrift服务主机
    :param port: 端口,默认9090
    :param timeout: 超时时间(毫秒)
    :return: Connection对象
    """
    try:
        # 创建连接,指定transport和protocol
        connection = happybase.Connection(
            host=host,
            port=port,
            timeout=timeout,
            # 使用buffered transport和binary protocol,这是常见配置
            transport='buffered',
            protocol='binary',
            # 如果HBase配置了认证,可能需要设置其他参数
            # autoconnect=False  # 可以手动控制连接
        )
        # 测试连接
        connection.open()
        print("连接HBase成功")
        return connection
    except Exception as e:
        print(f"连接HBase失败: {e}")
        return None

def basic_operations(connection):
    """基本操作示例"""
    if not connection:
        return
    
    # 获取表列表
    tables = connection.tables()
    print(f"现有表: {tables}")
    
    # 创建表(如果不存在)
    table_name = 'test_table'
    if table_name.encode() not in tables:
        families = {
            'cf1': dict(),  # 列族
            'cf2': dict()
        }
        connection.create_table(table_name, families)
        print(f"表 {table_name} 创建成功")
    
    # 获取表对象
    table = connection.table(table_name)
    
    # 插入数据
    table.put(
        b'row1',
        {
            b'cf1:col1': b'value1',
            b'cf2:col2': b'value2'
        }
    )
    print("数据插入成功")
    
    # 读取数据
    row = table.row(b'row1')
    print(f"读取数据: {row}")
    
    # 扫描数据
    for key, data in table.scan():
        print(f"扫描到: {key} -> {data}")
    
    # 删除数据
    table.delete(b'row1')
    print("数据删除成功")

if __name__ == '__main__':
    # 连接HBase
    conn = connect_hbase(host='your_hbase_host')  # 替换为实际主机
    
    if conn:
        try:
            # 执行基本操作
            basic_operations(conn)
        finally:
            # 关闭连接
            conn.close()
            print("连接已关闭")

常见验证问题及解决:

  1. 连接超时:检查HBase Thrift服务是否启动,防火墙是否开放9090端口。
  2. 协议不匹配:确保Thrift服务使用的协议与客户端一致(通常是binary)。
  3. 认证失败:如果HBase启用了安全认证(如Kerberos),需要额外配置:
    connection = happybase.Connection(
        host='host',
        port=9090,
        timeout=5000,
        # 如果使用Kerberos认证
        use_kerberos=True,
        # 其他认证参数...
    )
    
  4. 版本兼容性:确保happybase版本与HBase版本兼容。

一句话总结: 用happybase库并正确配置transport/protocol参数,注意服务端和客户端的协议匹配。


加白名單

谢谢,正是这样

回到顶部