<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>sample &#8211; 编码无悔 /  Intent &amp; Focused</title>
	<atom:link href="https://www.codelast.com/tag/sample/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codelast.com</link>
	<description>最优化之路</description>
	<lastBuildDate>Sun, 03 May 2020 12:36:06 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>[原创]使用C++（通过Thrift）访问/操作/读写Hbase</title>
		<link>https://www.codelast.com/%e5%8e%9f%e5%88%9b%e4%bd%bf%e7%94%a8c%ef%bc%88%e9%80%9a%e8%bf%87thrift%ef%bc%89%e8%ae%bf%e9%97%aehbase/</link>
					<comments>https://www.codelast.com/%e5%8e%9f%e5%88%9b%e4%bd%bf%e7%94%a8c%ef%bc%88%e9%80%9a%e8%bf%87thrift%ef%bc%89%e8%ae%bf%e9%97%aehbase/#comments</comments>
		
		<dc:creator><![CDATA[learnhard]]></dc:creator>
		<pubDate>Thu, 01 Sep 2011 05:40:43 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[原创]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Boost]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[client]]></category>
		<category><![CDATA[connect]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[Hbase]]></category>
		<category><![CDATA[how to]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[libevent]]></category>
		<category><![CDATA[operate]]></category>
		<category><![CDATA[read]]></category>
		<category><![CDATA[sample]]></category>
		<category><![CDATA[Thrift]]></category>
		<category><![CDATA[write]]></category>
		<category><![CDATA[例子]]></category>
		<category><![CDATA[操作Hbase]]></category>
		<category><![CDATA[教程]]></category>
		<category><![CDATA[方法]]></category>
		<category><![CDATA[示例]]></category>
		<category><![CDATA[访问]]></category>
		<category><![CDATA[访问Hbase]]></category>
		<category><![CDATA[读写]]></category>
		<category><![CDATA[读写HBase]]></category>
		<category><![CDATA[读取]]></category>
		<guid isPermaLink="false">http://www.codelast.com/?p=3303</guid>

					<description><![CDATA[<p>
	<span style="font-family: 宋体; font-size: 14px;">无奈，网上关于C++访问Hbase的文章实在太少，所以只好自己折腾一下，然后写出来了。</span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">要使用C++访问Hbase，可以走的途径少之又少，据说当前最好的方法就是通过Thrift来实现：</span></span></span><span style="font-size: 14px;"><span style="font-family: 宋体;"><a href="http://thrift.apache.org/" target="_blank" rel="noopener noreferrer"><span style="color: #000000;">http://thrift.apache.org/</span></a></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">所以本文分成几部分：（1）安装Thrift；（2）用Thrift 生成访问Hbase所需的C++文件；（3）在程序中通过Thrift来访问Hbase。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">另外，本文只包含读写Hbase数据的例子，不包含配置Hbase的方法，如需这些内容，请自行搜索。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">首先声明一下，本文基于以下环境：<br />
	<span id="more-3303"></span><!--more--><!--more--><!--more--><!--more--><!--more--><!--more--></span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">操作系统：RHEL 5.3，64位</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">Thrift 版本：0.7.0</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">要访问的 Hbase 版本：0.20.6</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">我使用0.90.4的 Hbase 安装包来生成C++所需的Hbase.h等文件（用新版的应该能兼容旧版的）</span></span></span></p>
<p>
	<span style="color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; font-size: 14px; line-height: 20px; text-align: left; background-color: rgb(255, 255, 255); ">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255); ">http://www.codelast.com/</span></a></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">下面开始，一步步来。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">（1）安装Thrift</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">不是一件很轻松的事。如果你的系统比较干净，可能很顺利地就搞定了，如果有依赖库缺失问题或者库冲突问题，那么就只能根据具体情况，一个个问题去fix了，谁知道会有多少麻烦。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">我运气比较好，在一个干净的系统上，很快就完成了。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">Thrift 至少会依赖于两个系统中一般不会带的库：libevent，boost。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">libevent 到这里下载：</span></span></span><span style="font-size: 14px;"><span style="font-family: 宋体;"><a href="http://monkey.org/~provos/libevent/" target="_blank" rel="noopener noreferrer"><span style="color: #000000;">http://monkey.org/~provos/libevent/</span></a></span></span><span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">&#160; 我使用的版本是：2.0.12-stable</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">boost 到这里下载：</span></span></span><span style="font-size: 14px;"><span style="font-family: 宋体;"><a href="http://www.boost.org/" target="_blank" rel="noopener noreferrer"><span style="color: #000000;">http://www.boost.org/</span></a></span></span><span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">&#160; 我使用的版本是：1.47.0</span></span></span></p>
<p>
	<span style="color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; font-size: 14px; line-height: 20px; text-align: left; background-color: rgb(255, 255, 255); ">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255); ">http://www.codelast.com/</span></a></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">安装libevent：</span></span></p>
<pre class="brush:shell;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
./configure --prefix=/usr/local/libevent
make
make install</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">安装boost（boost不像一般的Linux源码安装包一样，它的安装不是configure，make，make install，有点怪）：</span></span></p>
<pre class="brush:shell;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
./bootstrap.sh</pre>&#8230; <a href="https://www.codelast.com/%e5%8e%9f%e5%88%9b%e4%bd%bf%e7%94%a8c%ef%bc%88%e9%80%9a%e8%bf%87thrift%ef%bc%89%e8%ae%bf%e9%97%aehbase/" class="read-more">Read More </a>]]></description>
										<content:encoded><![CDATA[<p>
	<span style="font-family: 宋体; font-size: 14px;">无奈，网上关于C++访问Hbase的文章实在太少，所以只好自己折腾一下，然后写出来了。</span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">要使用C++访问Hbase，可以走的途径少之又少，据说当前最好的方法就是通过Thrift来实现：</span></span></span><span style="font-size: 14px;"><span style="font-family: 宋体;"><a href="http://thrift.apache.org/" target="_blank" rel="noopener noreferrer"><span style="color: #000000;">http://thrift.apache.org/</span></a></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">所以本文分成几部分：（1）安装Thrift；（2）用Thrift 生成访问Hbase所需的C++文件；（3）在程序中通过Thrift来访问Hbase。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">另外，本文只包含读写Hbase数据的例子，不包含配置Hbase的方法，如需这些内容，请自行搜索。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">首先声明一下，本文基于以下环境：<br />
	<span id="more-3303"></span><!--more--><!--more--><!--more--><!--more--><!--more--><!--more--></span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">操作系统：RHEL 5.3，64位</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">Thrift 版本：0.7.0</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">要访问的 Hbase 版本：0.20.6</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">我使用0.90.4的 Hbase 安装包来生成C++所需的Hbase.h等文件（用新版的应该能兼容旧版的）</span></span></span></p>
<p>
	<span style="color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; font-size: 14px; line-height: 20px; text-align: left; background-color: rgb(255, 255, 255); ">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255); ">http://www.codelast.com/</span></a></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">下面开始，一步步来。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">（1）安装Thrift</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">不是一件很轻松的事。如果你的系统比较干净，可能很顺利地就搞定了，如果有依赖库缺失问题或者库冲突问题，那么就只能根据具体情况，一个个问题去fix了，谁知道会有多少麻烦。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">我运气比较好，在一个干净的系统上，很快就完成了。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">Thrift 至少会依赖于两个系统中一般不会带的库：libevent，boost。</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">libevent 到这里下载：</span></span></span><span style="font-size: 14px;"><span style="font-family: 宋体;"><a href="http://monkey.org/~provos/libevent/" target="_blank" rel="noopener noreferrer"><span style="color: #000000;">http://monkey.org/~provos/libevent/</span></a></span></span><span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">&nbsp; 我使用的版本是：2.0.12-stable</span></span></span></p>
<p>
	<span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">boost 到这里下载：</span></span></span><span style="font-size: 14px;"><span style="font-family: 宋体;"><a href="http://www.boost.org/" target="_blank" rel="noopener noreferrer"><span style="color: #000000;">http://www.boost.org/</span></a></span></span><span style="color: #000000;"><span style="font-size: 14px;"><span style="font-family: 宋体;">&nbsp; 我使用的版本是：1.47.0</span></span></span></p>
<p>
	<span style="color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; font-size: 14px; line-height: 20px; text-align: left; background-color: rgb(255, 255, 255); ">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255); ">http://www.codelast.com/</span></a></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">安装libevent：</span></span></p>
<pre class="brush:shell;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
./configure --prefix=/usr/local/libevent
make
make install</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">安装boost（boost不像一般的Linux源码安装包一样，它的安装不是configure，make，make install，有点怪）：</span></span></p>
<pre class="brush:shell;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
./bootstrap.sh --prefix=/usr/local/boost</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">不出错的话接着执行以下命令开始编译（也可以通过编辑project-config.jam文件调整编译参数）：</span></span></p>
<pre class="brush:shell;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
./b2
./b2 install</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">安装Thrift：</span></span></p>
<pre class="brush:shell;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
chmod +x configure
./configure --with-boost=/usr/local --prefix=/usr/local/thrift
make
make install</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">至此，安装Thrift 的工作就完成了。</span></span></p>
<p>
	<span style="color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; font-size: 14px; line-height: 20px; text-align: left; background-color: rgb(255, 255, 255); ">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255); ">http://www.codelast.com/</span></a></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">（2）用Thrift 生成访问Hbase所需的C++文件</span></span></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">访问Hbase需要在你的程序中使用若干.h，.cpp文件，这些文件是用 Thrift 生成的。</span></span></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">解压Hbase源码安装包：</span></span></p>
<pre class="brush:shell;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
tar zxf hbase-0.90.4.tar.gz
cd hbase-0.90.4</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">在解压出来的文件中， 你可以找到一个名为 Hbase.thrift 的文件，这个文件定义了如何通过 Thrift 接口来访问Hbase。用这个Thrift文件，可以生成访问Hbase所需的C++文件：</span></span></p>
<pre class="brush:shell;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
/usr/local/thrift/bin/thrift --gen cpp ./src/main/resources/org/apache/hadoop/hbase/thrift/Hbase.thrift</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">会发现生成了gen-cpp目录：</span></span></p>
<pre class="brush:shell;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
ls gen-cpp/</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">输出：</span></span></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;"><span style="color: #0000ff;">Hbase_constants.cpp &nbsp;Hbase_constants.h &nbsp;Hbase.cpp &nbsp;Hbase.h &nbsp;Hbase_server.skeleton.cpp &nbsp;Hbase_types.cpp &nbsp;Hbase_types.h</span></span></span></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">除了Hbase_server.skeleton.cpp之外，其余文件都是在我们的程序里要用到的，将它们拷贝到我们的工程目录下。</span></span></p>
<p>
	<span style="color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; font-size: 14px; line-height: 20px; text-align: left; background-color: rgb(255, 255, 255); ">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255); ">http://www.codelast.com/</span></a></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">（3）在程序中使用Thrift来访问Hbase</span></span></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">要能通过 Thrift 访问Hbase，你必须首先要打开HBase的 Thrift 服务，请参考其他文档确保这一点是可用的。</span></span></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">下一步，我们在程序中如何读取Hbase的数据？</span></span></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">我们先看看hbase源码安装包中自带的例子：在解压出来的安装包中的&nbsp;examples/thrift/ 目录下的&nbsp;DemoClient.cpp 文件，有如下代码：</span></span></p>
<div>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
  boost::shared_ptr&lt;TTransport&gt; socket(new TSocket(&quot;localhost&quot;, 9090));
  boost::shared_ptr&lt;TTransport&gt; transport(new TBufferedTransport(socket));
  boost::shared_ptr&lt;TProtocol&gt; protocol(new TBinaryProtocol(transport));
  HbaseClient client(protocol);
  try {
    transport-&gt;open();

    // do something

    transport-&gt;close();
  } catch (TException &amp;tx) {
    printf(&quot;ERROR: %s\n&quot;, tx.what());
  }</pre>
</div>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">我们就仿照这个例子来做。从DemoClient.cpp可见，我们要先创建三个指针socket，transport和protocol，后两个分别依赖于前两个，最后再创建一个client对象，我们操作Hbase就是使用这个client对象。在操作Hbase前，需要先打开到Hbase Thrift service的连接，即 transport-&gt;open()，在操作完 Hbase之后，需要关闭连接，即 transport-&gt;close()，这下就比较清楚了：我们可以写一个自己的类CHbaseOperate，它应该有一个connect函数和一个disconnect函数，分别用于打开、关闭连接，还应该有读写Hbase的基本功能。读写Hbase的方法，请参考Hbase.h中的函数，例子还是看DemoClient.cpp。</span></span><br />
	<span style="color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; font-size: 14px; line-height: 20px; text-align: left; background-color: rgb(255, 255, 255); ">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255); ">http://www.codelast.com/</span></a></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">下面上代码：<br />
	<span style="background-color: #00ff00;">HbaseOperate.h：</span></span></span></p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
#ifndef __HBASE_OPERATE_H
#define __HBASE_OPERATE_H

#include &lt;string&gt;
#include &lt;protocol/TBinaryProtocol.h&gt;
#include &lt;transport/TSocket.h&gt;
#include &lt;transport/TTransportUtils.h&gt;
#include &quot;Hbase.h&quot;

/**
 * Class to operate Hbase.
 *
 * @author Darran Zhang (codelast.com)
 * @version 11-08-24
 * @declaration These codes are only for non-commercial use, and are distributed on an &quot;AS IS&quot; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
 * You must not remove this declaration at any time.
 */

using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace apache::hadoop::hbase::thrift;

typedef struct hbaseRet {
  std::string rowValue;
  time_t ts;

  hbaseRet() {
    ts = 0;
  }

} hbaseRet;

class CHbaseOperate
{
public:
	CHbaseOperate();
	virtual ~CHbaseOperate();

private:
  boost::shared_ptr&lt;TTransport&gt; socket;
  boost::shared_ptr&lt;TTransport&gt; transport;
  boost::shared_ptr&lt;TProtocol&gt; protocol;

  HbaseClient *client;

  std::string  hbaseServiceHost;
  int     hbaseServicePort;
  bool    isConnected;

public:
  bool  connect();

  bool  connect(std::string host, int port);

  bool  disconnect();

  bool  putRow(const std::string &amp;tableName,
              const std::string &amp;rowKey,
              const std::string &amp;column,
              const std::string &amp;rowValue);

  bool  getRow(hbaseRet &amp;result,
              const std::string &amp;tableName,
              const std::string &amp;rowKey,
              const std::string &amp;columnName);
};

#endif</pre>
<p>
	<span style="color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; font-size: 14px; line-height: 20px; text-align: left; background-color: rgb(255, 255, 255); ">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255); ">http://www.codelast.com/</span></a></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;"><span style="background-color: #00ff00;">HbaseOperate.cpp：</span></span></span></p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
#include &quot;HbaseOperate.h&quot;
#include &quot;log4cxx/log4cxx.h&quot;
#include &quot;log4cxx/propertyconfigurator.h&quot;

static log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(&quot;HbaseOperate.cpp&quot;));

/**
 * Class to operate Hbase.
 *
 * @author Darran Zhang (codelast.com)
 * @version 11-08-24
 * @declaration These codes are only for non-commercial use, and are distributed on an &quot;AS IS&quot; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
 * You must not remove this declaration at any time.
 */

using namespace std;

CHbaseOperate::CHbaseOperate() :
socket((TSocket*)NULL), transport((TBufferedTransport*)NULL), protocol((TBinaryProtocol*)NULL), client(NULL), hbaseServicePort(9090), isConnected(false)
{
}

CHbaseOperate::~CHbaseOperate()
{
  if (isConnected) {
    disconnect();
  }
  if (NULL != client) {
    delete client;
    client = NULL;
  }
}

/**
 * Connect Hbase.
 *
 */
bool CHbaseOperate::connect()
{
  if (isConnected) {
    LOG4CXX_INFO(logger, &quot;Already connected, don&#39;t need to connect it again&quot;);
    return true;
  }

  try {
    socket.reset(new TSocket(hbaseServiceHost, hbaseServicePort));
    transport.reset(new TBufferedTransport(socket));
    protocol.reset(new TBinaryProtocol(transport));

    client = new HbaseClient(protocol);

    transport-&gt;open();
  } catch (const TException &amp;tx) {
    LOG4CXX_ERROR(logger, &quot;Connect Hbase error : &quot; &lt;&lt; tx.what());
    return false;
  }

  isConnected = true;
  return isConnected;
}

/**
 * Connect Hbase.
 *
 */
bool CHbaseOperate::connect(std::string host, int port)
{
  hbaseServiceHost = host;
  hbaseServicePort = port;

  return connect();
}

/**
 * Disconnect from Hbase.
 *
 */
bool CHbaseOperate::disconnect()
{
  if (!isConnected) {
    LOG4CXX_ERROR(logger, &quot;Haven&#39;t connected to Hbase yet, can&#39;t disconnect from it&quot;);
    return false;
  }

  if (NULL != transport) {
    try {
      transport-&gt;close();
    } catch (const TException &amp;tx) {
      LOG4CXX_ERROR(logger, &quot;Disconnect Hbase error : &quot; &lt;&lt; tx.what());
      return false;
    }
  } else {
    return false;
  }

  isConnected = false;
  return true;
}

/**
 * Put a row to Hbase.
 *
 * @param tableName   [IN] The table name.
 * @param rowKey      [IN] The row key.
 * @param column      [IN] The &quot;column family : qualifier&quot;.
 * @param rowValue    [IN] The row value.
 * @return True for successfully put the row, false otherwise.
 */
bool CHbaseOperate::putRow(const string &amp;tableName, const string &amp;rowKey, const string &amp;column, const string &amp;rowValue)
{
  if (!isConnected) {
    LOG4CXX_ERROR(logger, &quot;Haven&#39;t connected to Hbase yet, can&#39;t put row&quot;);
    return false;
  }

  try {
    std::vector&lt;Mutation&gt; mutations;
    mutations.push_back(Mutation());
    mutations.back().column = column;
    mutations.back().value = rowValue;
    client-&gt;mutateRow(tableName, rowKey, mutations);

  } catch (const TException &amp;tx) {
    LOG4CXX_ERROR(logger, &quot;Operate Hbase error : &quot; &lt;&lt; tx.what());
    return false;
  }

  return true;
}

/**
 * Get a Hbase row.
 *
 * @param result      [OUT] The object which contains the returned data.
 * @param tableName   [IN] The Hbase table name, e.g. &quot;MyTable&quot;.
 * @param rowKey      [IN] The Hbase row key, e.g. &quot;kdr23790&quot;.
 * @param columnName  [IN] The &quot;column family : qualifier&quot;.
 * @return True for successfully get the row, false otherwise.
 */
bool CHbaseOperate::getRow(hbaseRet &amp;result, const std::string &amp;tableName, const std::string &amp;rowKey, const std::string &amp;columnName)
{
  if (!isConnected) {
    LOG4CXX_ERROR(logger, &quot;Haven&#39;t connected to Hbase yet, can&#39;t read data from it&quot;);
    return false;
  }

  std::vector&lt;std::string&gt; columnNames;
  columnNames.push_back(columnName);

  std::vector&lt;TRowResult&gt; rowResult;
  try {
    client-&gt;getRowWithColumns(rowResult, tableName, rowKey, columnNames);
  } catch (const TException &amp;tx) {
    LOG4CXX_ERROR(logger, &quot;Operate Hbase error : &quot; &lt;&lt; tx.what());
    return false;
  }

  if (0 == rowResult.size()) {
    LOG4CXX_WARN(logger, &quot;Got no record with the key : [&quot; &lt;&lt; rowKey &lt;&lt; &quot;]&quot;);
    return false;
  }

  std::map&lt;std::string, TCell&gt;::const_iterator it = rowResult[rowResult.size() -1].columns.begin();
  result.rowValue = it-&gt;second.value;
  result.ts = it-&gt;second.timestamp;

  return true;
}</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">注意我在程序中使用了<a href="http://logging.apache.org/log4cxx/" target="_blank" rel="noopener noreferrer">Apache log4cxx</a>这个记录日志的库来打印/保存程序运行日志，使用方法可参考<span style="color: #ff0000;">【</span><a href="http://www.codelast.com/?p=3211" target="_blank" rel="noopener noreferrer">此链接</a><span style="color: #ff0000;">】</span>。如果你不想用，可以自己改为std::cout。<br />
	代码有了，使用方法为：可以在你的程序中创建一个全局对象：</span></span></p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
CHbaseOperate g_ho;</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">在需要操作Hbase之前：</span></span></p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
g_ho.connect(&quot;192.168.55.66&quot;, 9090);</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;">其中，&ldquo;192.168.55.66&rdquo;和9090分别是你的Hbase Thrift service的服务器地址和端口号，你需要正确地配置好，才能使用。本文开头已经说了，本文不讨论这方面的问题。<br />
	在操作完Hbase之后：</span></span></p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
g_ho.disconnect();</pre>
<p>
	<span style="color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; font-size: 14px; line-height: 20px; text-align: left; background-color: rgb(255, 255, 255); ">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255); ">http://www.codelast.com/</span></a><br />
	<span style="font-size: 14px;"><span style="font-family: 宋体;"> <span style="color: #000000;">现在再来说一下读写操作Hbase的两个函数：putRow()和getRow()。<br />
	<span style="background-color: #40e0d0;">putRow()：</span></span></span></span></p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
bool  putRow(const std::string &amp;tableName,
              const std::string &amp;rowKey,
              const std::string &amp;column,
              const std::string &amp;rowValue);</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;"><span style="color: #000000;">这是向Hbase写入一条记录的函数，参数tableName为Hbase表名，即你要将记录写到哪个Hbase表中；参数rowKey为待写入的记录的key；参数column为待写入的记录的&ldquo;column family:qualifier&rdquo;组合，参数rowValue为待写入的记录的value。</span></span></span></p>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;"><span style="background-color: #40e0d0;">getRow()：</span></span></span></p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
bool  getRow(hbaseRet &amp;result,
              const std::string &amp;tableName,
              const std::string &amp;rowKey,
              const std::string &amp;columnName);</pre>
<p>
	<span style="font-size: 14px;"><span style="font-family: 宋体;"><span style="color: #000000;">这是从Hbase中读取一条记录的函数，参数tableName为Hbase表名，即你要从哪个Hbase表中读取记录；参数rowKey为你要查询的记录的key；参数columnName为你要查询的记录的&ldquo;column family:qualifier&rdquo;组合;参数result为返回的Hbase的数据，它包含记录的value和记录的时间戳：</span></span></span></p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
typedef struct hbaseRet {
  std::string rowValue;
  time_t ts; 

  hbaseRet() {
    ts = 0;
  }

} hbaseRet;</pre>
<p>
	<span style="color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; font-size: 14px; line-height: 20px; text-align: left; background-color: rgb(255, 255, 255); ">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255); ">http://www.codelast.com/</span></a><br />
	<span style="font-size: 14px;"><span style="font-family: 宋体;"> <span style="color: #000000;">至于操作的结果对不对，可以在Hbase shell中用get, scan等命令来验证，具体方法请看Hbase shell的help。另外，最好再写一些unit test来测试。<br />
	如果你要为CHbaseOperate类添加功能，可以参考Hbase.h文件中的函数定义。如你所见，CHbaseOperate类主要也是调用了里面的函数，只不过这个类可以让一些不太熟悉Hbase概念的人可以更方便地操作Hbase罢了。</span></span></span></p>
<p>	<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="https://www.codelast.com/" rel="noopener noreferrer" target="_blank"><span style="color: rgb(255, 255, 255);">https://www.codelast.com/</span></a><br />
	<span style="color: rgb(255, 0, 0);">➤➤</span>&nbsp;版权声明&nbsp;<span style="color: rgb(255, 0, 0);">➤➤</span>&nbsp;<br />
	转载需注明出处：<u><a href="https://www.codelast.com/" rel="noopener noreferrer" target="_blank"><em><span style="color: rgb(0, 0, 255);"><strong style="font-size: 16px;"><span style="font-family: arial, helvetica, sans-serif;">codelast.com</span></strong></span></em></a></u>&nbsp;<br />
	感谢关注我的微信公众号（微信扫一扫）：</p>
<p style="border: 0px; font-size: 13px; margin: 0px 0px 9px; outline: 0px; padding: 0px; color: rgb(77, 77, 77);">
	<img decoding="async" alt="wechat qrcode of codelast" src="https://www.codelast.com/codelast_wechat_qr_code.jpg" style="width: 200px; height: 200px;" /></p>

			<!--[syntaxhighlighter]-->
			<!--代码高亮，请勿编辑-->
			<script type="text/javascript" src="https://www.codelast.com/wp-content/plugins/ck-and-syntaxhighlighter/syntaxhighlighter/scripts/shCore.js"></script><script type="text/javascript" src="https://www.codelast.com/wp-content/plugins/ck-and-syntaxhighlighter/syntaxhighlighter/scripts/shBrushShell.js"></script>
<script type="text/javascript" src="https://www.codelast.com/wp-content/plugins/ck-and-syntaxhighlighter/syntaxhighlighter/scripts/shBrushCpp.js"></script>

			<link type="text/css" rel="stylesheet" href="https://www.codelast.com/wp-content/plugins/ck-and-syntaxhighlighter/syntaxhighlighter/styles/shCoreCk.css" />
			<link type="text/css" rel="stylesheet" href="https://www.codelast.com/wp-content/plugins/ck-and-syntaxhighlighter/syntaxhighlighter/styles/shThemeCk.css" />
			<script type="text/javascript">
			SyntaxHighlighter.defaults['class-name']	= '';
			SyntaxHighlighter.defaults['smart-tabs']	= true;
			SyntaxHighlighter.defaults['tab-size']		= 2;
			SyntaxHighlighter.defaults['gutter']		= true;
			SyntaxHighlighter.defaults['quick-code']	= true;
			SyntaxHighlighter.defaults['collapse'] 		= false;
			SyntaxHighlighter.defaults['auto-links']	= true;
			SyntaxHighlighter.defaults['toolbar']		= true;
			SyntaxHighlighter.all();
			</script>
			<!--[/syntaxhighlighter]-->]]></content:encoded>
					
					<wfw:commentRss>https://www.codelast.com/%e5%8e%9f%e5%88%9b%e4%bd%bf%e7%94%a8c%ef%bc%88%e9%80%9a%e8%bf%87thrift%ef%bc%89%e8%ae%bf%e9%97%aehbase/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
	</channel>
</rss>
