`
haoningabc
  • 浏览: 1456509 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

thirft连接hbase的例子

阅读更多
hbase支持的thrift有两种方式
thrift和
thrift2
官方似乎推荐thrift2
一下是两种thrift的java客户端的连接方式
然后是一个cpp以thrift2的方式连接hbase的操作
如果是使用thrift1
hbase-daemon.sh start thrift
如果是使用thrift2
hbase-daemon.sh start thrift2
官方例子在
/data/hadoop/hbase/hbase-0.94.17/src/examples/thrift
thrift文件在
./src/main/resources/org/apache/hadoop/hbase/thrift/Hbase.thrift
thrift2 的例子在
/data/hadoop/hbase/hbase-0.94.17/src/examples/thrift2
thrift2文件在
./src/main/resources/org/apache/hadoop/hbase/thrift2/hbase.thrift
(只有java和python的)


先生成文件
thrift -r --gen java Hbase.thrift
客户端代码
HaoClient.java
package org.apache.hadoop.hbase.thrift.generated;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

public class HaoClient {
	public static String byteBufferToString(ByteBuffer buffer) {
		CharBuffer charBuffer = null;
		try {
			Charset charset = Charset.forName("UTF-8");
			CharsetDecoder decoder = charset.newDecoder();
			charBuffer = decoder.decode(buffer);
			buffer.flip();
			return charBuffer.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	public static ByteBuffer getByteBuffer(String str) {
		return ByteBuffer.wrap(str.getBytes());
	}
	private void start() {
		try {
			TTransport socket = new TSocket("10.230.13.100", 9090);// 我的虚拟机,线上用的thrift2
			TProtocol protocol = new TBinaryProtocol(socket, true, true);// 注意这里
			Hbase.Client client = new Hbase.Client(protocol);
			socket.open();
			System.out.println("open");
			try {
				System.out.println("scanning tables...");
				for (ByteBuffer name : client.getTableNames()) {
					System.out.println("find:" + byteBufferToString(name));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			socket.close();
			System.out.println("close");
		} catch (TTransportException e) {
			e.printStackTrace();
		} catch (TException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		HaoClient c = new HaoClient();
		c.start();

	}
}


如果是thrift2的话
hbase-daemon.sh start thrift2
thrift -r --gen java hbase.thrift
HaoClient2.java
package org.apache.hadoop.hbase.thrift2.generated;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class HaoClient2 {
	public static String byteBufferToString(ByteBuffer buffer) {
		CharBuffer charBuffer = null;
		try {
			Charset charset = Charset.forName("UTF-8");
			CharsetDecoder decoder = charset.newDecoder();
			charBuffer = decoder.decode(buffer);
			buffer.flip();
			return charBuffer.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	public static ByteBuffer getByteBuffer(String str) {
		return ByteBuffer.wrap(str.getBytes());
	}
    private void start() {
        try {
            TTransport socket = new TSocket("10.230.13.100", 9090);
            // TTransport socket = new TSocket("10.77.112.191",9090);
            //TTransport transport = new TFramedTransport(socket);
            // TProtocol protocol = new TCompactProtocol(socket);
            TProtocol protocol = new TBinaryProtocol(socket, true, true);//注意这里
            // THBaseService.Client client = new THBaseService.Client(protocol);
            THBaseService.Iface client = new THBaseService.Client(protocol);
            socket.open();
            System.out.println("open");
            ByteBuffer table = ByteBuffer.wrap("mytable".getBytes());

            /* TPut put = new TPut();
            put.setRow("first".getBytes());

            TColumnValue columnValue = new TColumnValue();
            columnValue.setFamily("cf".getBytes());
            columnValue.setQualifier("fromjava".getBytes());
            columnValue.setValue("java is ok".getBytes());
            List<TColumnValue> columnValues = new ArrayList<TColumnValue>();
            columnValues.add(columnValue);
            put.setColumnValues(columnValues);

            client.put(table, put);*/
            // byte[] aa=Bytes.toBytesBinary("\\x00\\x00\\x15o");
            TGet get = new TGet();
            get.setRow("first".getBytes());
            TResult result = client.get(table, get);
            System.out.println("row = " + new String(result.getRow()));
            for (TColumnValue resultColumnValue : result.getColumnValues()) {
              System.out.println("family = " + new String(resultColumnValue.getFamily()));
              System.out.println("qualifier = " + new String(resultColumnValue.getQualifier()));
              System.out.println("value = " + new String((resultColumnValue.getValue())));
              System.out.println("timestamp = " + resultColumnValue.getTimestamp());
              System.out.println("");
            }
            socket.close();
            System.out.println("close");
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HaoClient2 c = new HaoClient2();
        c.start();
    }
}



注意需要,thrift1的Hbase.thirft
thrift2的hbase.thirft
还需要生成的代码,和hbase所有的jar

hbase的thrift1 和thrift2生成的类不一样
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
如果是c++连接的话
官方只给了个java和py的例子,网上有很多thrift1的接口的,但是没找到thirft2 的
自己写了个客户端如下
c++代码如下
thrift -r --gen cpp hbase.thrift
[root@mytest HbaseThrift]# cat HbaseClient.cpp 
#include "THBaseService.h"
#include <config.h>
#include <vector>
#include <transport/TSocket.h>
#include <transport/TBufferTransports.h>
#include <protocol/TBinaryProtocol.h>

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace apache::hadoop::hbase::thrift2;

using boost::shared_ptr;

int main(int argc, char **argv) {
    boost::shared_ptr<TSocket> socket(new TSocket("10.230.13.100", 9090));
    boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
    boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));

    transport->open();
    printf("open\n");
    THBaseServiceClient client(protocol);
    TResult tresult;
    TGet get;
    //const std::string table="mytable";
    const std::string table("mytable");
    const std::string thisrow="first";
    get.__set_row(thisrow);
    //get.__set_row("first");
    client.get(tresult,table,get);
    vector<TColumnValue> list=tresult.columnValues;
    std::vector<TColumnValue>::const_iterator iter;
    for(iter=list.begin();iter!=list.end();iter++) {
      printf("list size: %d\n",list.size());
      printf("get : %s, %s,%s\n",(*iter).family.c_str(),(*iter).qualifier.c_str(),(*iter).value.c_str());//,(*iter).timestamp
    }    

    transport->close();
    printf("close\n");
    return 0;
}
[root@mytest HbaseThrift]# 

Makefile如下
[root@mytest HbaseThrift]# cat Makefile 
BOOST_DIR = /usr/include/boost
THRIFT_DIR = /usr/local/thrift/include/thrift
#LIB_DIR = /usr/local/lib
LIB_DIR = /usr/local/thrift/lib/
GEN_SRC = ./gen-cpp/hbase_types.cpp ./gen-cpp/hbase_constants.cpp ./gen-cpp/THBaseService.cpp
default: client
client: HbaseClient.cpp
        g++ -g -o HbaseClient -lm -pthread -lz -lrt -lssl -I${THRIFT_DIR} -I${BOOST_DIR}  -I./gen-cpp -L${LIB_DIR} -lthrift HbaseClient.cpp ${GEN_SRC}
clean:
        $(RM) -r HbaseClient


[root@mytest HbaseThrift]# 

代码目录
[root@mytest HbaseThrift]# tree
.
├── gen-cpp
│   ├── hbase_constants.cpp
│   ├── hbase_constants.h
│   ├── hbase_types.cpp
│   ├── hbase_types.h
│   ├── THBaseService.cpp
│   ├── THBaseService.h
│   └── THBaseService_server.skeleton.cpp
├── HbaseClient.cpp
├── hbase.thrift
└── Makefile

1 directory, 10 files
[root@mytest HbaseThrift]#
[root@mytest HbaseThrift]# ls
gen-cpp  HbaseClient  HbaseClient.cpp  hbase.thrift  Makefile
hbase需要先建立:
hbase shell
create 'mytable','cf'

[root@mytest HbaseThrift]# ./HbaseClient
open
list size: 4
get : cf, cf,value1
list size: 4
get : cf, foo,7
list size: 4
get : cf, fromjava,java is ok
list size: 4
get : cf, message,hello haonings hbase
close
[root@mytest HbaseThrift]#
注意设置
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib:/usr/local/thrift/lib
找thrift的so

插入的例子
[root@mytest HbaseThrift]# cat HbaseClient.cpp
#include "THBaseService.h"
#include <config.h>
#include <vector>
#include <transport/TSocket.h>
#include <transport/TBufferTransports.h>
#include <protocol/TBinaryProtocol.h>

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace apache::hadoop::hbase::thrift2;

using boost::shared_ptr;

int main(int argc, char **argv) {
//    boost::shared_ptr<TSocket> socket(new TSocket("10.217.12.179", 9090));
    boost::shared_ptr<TSocket> socket(new TSocket("10.77.112.191", 9090));
    boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
    boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));

    transport->open();
    TPut put;
    THBaseServiceClient client(protocol);
    const std::string table="mytable";
    const std::string thisrow="second";
    put.__set_row(thisrow);
    TColumnValue columnValue;
    const std::string thisfamily="cf";
    columnValue.__set_family(thisfamily);
    const std::string thisqualifier="fromcpp";
    columnValue.__set_qualifier(thisqualifier);
    const std::string thisvalue="vppisok";
    columnValue.__set_value(thisvalue);
    columnValue.__set_timestamp(1395036661654);
    vector<TColumnValue> columnValues;
    columnValues.push_back(columnValue);
    put.__set_columnValues(columnValues);
//    std::cout<<"Texception"<<std::endl;
   /* try{

    }catch(TException &e){

    }*/
    client.put(table,put);
    /*printf("open\n");
    THBaseServiceClient client(protocol);
    TResult tresult;
    TGet get;
    //const std::string table="mytable";
    const std::string table("mytable");
    const std::string thisrow="first";
    get.__set_row(thisrow);
    //get.__set_row("first");
    client.get(tresult,table,get);
    vector<TColumnValue> list=tresult.columnValues;
    std::vector<TColumnValue>::const_iterator iter;
    for(iter=list.begin();iter!=list.end();iter++) {
      printf("list size: %d\n",list.size());
      printf("get : %s, %s,%s\n",(*iter).family.c_str(),(*iter).qualifier.c_str(),(*iter).value.c_str());//,(*iter).timestamp
    }    */

    transport->close();
    printf("close\n");
    return 0;
}
[root@mytest HbaseThrift]# 
分享到:
评论

相关推荐

    python通过thrift访问hbase.docx

    "Python 通过 Thrift 访问 HBase" 在大数据时代,HBase 作为一个分布式的、面向列的 NoSQL 数据库,广泛应用于大规模数据存储和处理中。Python 作为一门流行的编程语言,也提供了多种方式来访问 HBase。其中,...

    C#通过thrift连接hbase过程

    【C#通过Thrift连接Hbase过程】 在分布式大数据存储领域,Apache Hbase是一个流行的NoSQL数据库,它基于Google的Bigtable设计,并运行在Apache Hadoop之上。为了在不同的编程语言环境中与Hbase进行交互,Thrift(一...

    Python3通过thrift连接hbase库_修改版,个人已验证

    python3通过thrift连接hbase模块修改版,其中hbase-python3,里面的path,根据实际实际路径修改.

    Java通过thrift连接hbase.docx

    【Java通过Thrift连接HBase】\n\n在Java中,连接HBase通常涉及使用Thrift,这是一种轻量级的接口定义语言,可以用来构建跨语言的服务。Thrift允许我们定义数据类型和服务,然后自动生成各种语言(如Java)的代码,...

    thrift操作Hbase数据库

    使用Thrift生成的代码,我们需要实例化一个Hbase的客户端对象,然后通过这个对象建立到Hbase服务器的连接。连接通常需要指定服务器地址和端口。 4. **基本操作** - **创建表(Create Table)**: 需要指定表名和列...

    java代码使用thrift2操作hbase示例

    在本文中,我们将深入探讨如何使用Java通过Thrift2接口操作HBase数据库。HBase是一个分布式、可扩展的大数据存储系统,它构建于Hadoop之上,支持实时读写。Thrift是一个轻量级的框架,用于跨语言服务开发,允许不同...

    go thrift访问hbase

    博客配套文件,详细演示了go通过thrift1和thrift2接口访问hbase的方法,并给出了批量访问的简单封装接口。

    python3 使用 thrift 操作hbase 安装hbase-thirft后有一个Hbase报错

    python3 使用 thrift 操作hbase 安装hbase-thirft后有一个Hbase报错 使用这个修改完成的Hbase类替换掉原来的Hbase类问题全部解决 主要是因为python版本兼容性带来的问题

    C#使用Thrift2操作HBase数据库

    4. **连接HBase**: 在C#代码中,创建Thrift客户端实例,配置连接信息,如HBase服务器地址和端口。 5. **实例化HBase服务**: 使用客户端连接到HBase,实例化服务代理。 6. **执行操作**: 通过服务代理调用HBase的...

    Laravel开发-thrift-hbase-laravel

    本文将详细介绍如何在Laravel项目中集成Thrift与HBase,以实现对HBase数据库的操作。 首先,我们需要在Laravel项目中安装Thrift库。这通常通过Composer完成,Laravel的依赖管理工具。运行以下命令将Thrift添加到...

    python thrift2 connect hbase

    在Python中使用Thrift2连接HBase,首先需要安装thrift库,可以使用pip命令进行安装: ``` pip install thrift ``` 接着,你需要下载HBase的Thrift IDL文件(通常为hbase.thrift),这个文件定义了HBase服务的所有...

    通过thrift使用c++访问hbase

    【标题】: "通过Thrift使用C++访问HBase" 【描述】: "本文档详述了如何在Linux和Windows环境下配置Thrift环境并使用HBase的C++客户端。" 【标签】: "hadoop hbase thrift boost" 在IT领域,特别是大数据处理中,...

    golang connect hbase thrift2

    在本文中,我们将深入探讨如何使用Golang连接到HBase数据库,特别是在最新的Thrift2协议下。Thrift是一种跨语言的服务开发工具,它允许我们定义服务接口,然后自动生成多种编程语言的代码,使得不同语言之间可以进行...

    C#通过thrift连接hbase操作步骤

     2、利用thrift-0.9.1.exe工具生成thrift连接hbase的客户端接口代码:  从hbase源码包目录  hbase-0.96.0-srchbase-0.96.0hbase-thriftsrcmainesourcesorgapachehadoophbase hrift  找到HBase.Thrift文件,...

    thrift1 查询hbase

    - **连接HBase**:使用Thrift客户端连接到运行Thrift服务的HBase节点。 - **打开表**:指定表名,获取表对象。 - **构造扫描器**:设置扫描条件,比如范围、过滤器等。 - **执行扫描**:使用扫描器遍历表中的行...

    java 通过thrift-0.9.1读取hbase表数据

    - 连接Thrift服务器:通过`TSocket`或`TFramedTransport`建立与HBase Thrift服务的连接。 - 创建HBase协议缓冲区:使用`TProtocol`包装传输对象,以便进行数据序列化和反序列化。 - 初始化客户端:实例化`Hbase....

    python3使用thrift操作hbase hbase-thirft报错解决

    python连接hbase需要用到hbase-thirft类库,但是hbase-thirft只在python2下能正常使用,如果在python3下,会报错,主要有一下几个错误 except IOError, io: SyntaxError: invalid syntax ModuleNotFoundError: No ...

    thrift生成好的python hbase库

    thrift生成好的python hbase库,配合thrift库可直接操作hbase

Global site tag (gtag.js) - Google Analytics