基于C#+Thrift操作HBase实践
在基于HBase数据库的开发中,对应Java语言来说,可以直接使用HBase的原生API来操作HBase表数据,当然你要是不嫌麻烦可以使用Thrift客户端Java API,这里有我曾经使用过的 HBase Thrift客户端Java API实践,可以参考。对于具有其他编程语言背景的开发人员,为
在基于HBase数据库的开发中,对应Java语言来说,可以直接使用HBase的原生API来操作HBase表数据,当然你要是不嫌麻烦可以使用Thrift客户端Java API,这里有我曾经使用过的 HBase Thrift客户端Java API实践,可以参考。对于具有其他编程语言背景的开发人员,为了获取HBase带来的好处,那么就可以选择使用HBase Thrift客户端对应编程语言的API,来实现与HBase的交互。
这里,我们使用C#客户端来操作HBase。HBase的Thrift接口的定义,可以通过链接http://svn.apache.org/viewvc/hbase/trunk/hbase-server/src/main/resources/org/apache/hadoop/hbase/thrift/Hbase.thrift?view=markup看到,我们需要安装Thrift编译器,才能生成HBase跨语言的API,这里,我使用的版本是0.9.0。需要注意的是,一定要保证,安装了某个版本Thrift的Thrift编译器,在导入对应语言库的时候,版本一定要统一,否则就会出现各种各样的问题,因为不同Thrift版本,对应编程语言的库API可能有变化。
首先,下载上面链接的内容,保存为Hbase.thrift。
然后,执行如下命令,生成C#编程语言的HBase Thrift客户端API:
[hadoop@master hbase]$ thrift --gen csharp Hbase.thrift [hadoop@master hbase]$ ls gen-csharp
这里,我们基于C#语言,使用HBase 的Thrift 客户端API访问HBase表。事实上,如果使用Java来实现对HBase表的操作,最好是使用HBase的原生API,无论从性能还是便利性方面,都会提供更好的体验。使用Thrift API访问,实际也是在HBase API之上进行了一层封装,可能初次使用Thrift API感觉很别扭,有时候还要参考Thrift服务端的实现代码。
准备工作如下:
- 下载Thrift软件包,解压缩后,拷贝thrift-0.9.0/lib/java/src下面的代码到工作区(开发工具中)
- 将上面生成的gen-csharp目录中代码拷贝到工作区
- 保证HBase集群正常运行,接着启动HBase的Thrift服务,执行如下命令:
bin/hbase thrift -b master -p 9090 start
上面,HBase的Thrift服务端口为9090,下面通过Thrift API访问的时候,需要用到,而不是HBase的服务端口(默认60000)。
接着,实现一个简单的例子,访问Hbase表。
首先,我们通过HBase Shell创建一个表:
create 'test_info', 'info'
表名为test_info,列簇名称为info。
然后,我们开始基于上面生成的Thrift代码来实现对HBase表的操作。
这里,我们实际上是对HBase Thrift客户端Java API实践中的Java代码进行了翻译,改写成C#语言的相关操作。我们在客户端,进行了一层抽象,更加便于传递各种参数,抽象类为AbstractHBaseThriftService,对应的命名空间为HbaseThrift.HBase.Thrift,该类实现代码如下所示:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Thrift.Transport; using Thrift.Protocol; namespace HbaseThrift.HBase.Thrift { public abstract class AbstractHBaseThriftService { protected static readonly string CHARSET = "UTF-8"; private string host = "localhost"; private int port = 9090; private readonly TTransport transport; protected readonly Hbase.Client client; public AbstractHBaseThriftService() : this("localhost", 9090) { } public AbstractHBaseThriftService(string host, int port) { this.host = host; this.port = port; transport = new TSocket(host, port); TProtocol protocol = new TBinaryProtocol(transport, true, true); client = new Hbase.Client(protocol); } public void Open() { if (transport != null) { transport.Open(); } } public void Close() { if (transport != null) { transport.Close(); } } public abstract List GetTables(); public abstract void Update(string table, string rowKey, bool writeToWal, string fieldName, string fieldValue, Dictionary attributes); public abstract void Update(string table, string rowKey, bool writeToWal, Dictionary fieldNameValues, Dictionary attributes); public abstract void DeleteCell(string table, string rowKey, bool writeToWal, string column, Dictionary attributes); public abstract void DeleteCells(string table, string rowKey, bool writeToWal, List columns, Dictionary attributes); public abstract void DeleteRow(string table, string rowKey, Dictionary attributes); public abstract int ScannerOpen(string table, string startRow, List columns, Dictionary attributes); public abstract int ScannerOpen(string table, string startRow, string stopRow, List columns, Dictionary attributes); public abstract int ScannerOpenWithPrefix(string table, string startAndPrefix, List columns, Dictionary attributes); public abstract int ScannerOpenTs(string table, string startRow, List columns, long timestamp, Dictionary attributes); public abstract int ScannerOpenTs(string table, string startRow, string stopRow, List columns, long timestamp, Dictionary attributes); public abstract List ScannerGetList(int id, int nbRows); public abstract List ScannerGet(int id); public abstract List GetRow(string table, string row, Dictionary attributes); public abstract List GetRows(string table, List rows, Dictionary attributes); public abstract List GetRowsWithColumns(string table, List rows, List columns, Dictionary attributes); public abstract void ScannerClose(int id); /** * Iterate result rows(just for test purpose) * @param result */ public abstract void IterateResults(TRowResult result); } }
这里,简单叙述一下,我们提供的客户端API的基本功能:
- 建立到Thrift服务的连接:Open()
- 获取到HBase中的所有表名:GetTables()
- 更新HBase表记录:Update()
- 删除HBase表中一行的记录的数据(cell):DeleteCell()和DeleCells()
- 删除HBase表中一行记录:deleteRow()
- 打开一个Scanner,返回id:ScannerOpen()、ScannerOpenWithPrefix()和ScannerOpenTs();然后用返回的id迭代记录:ScannerGetList()和ScannerGet()
- 获取一行记录结果:GetRow()、GetRows()和GetRowsWithColumns()
- 关闭一个Scanner:ScannerClose()
- 迭代结果,用于调试:IterateResults()
比如,我们想要实现分页的逻辑,可能和传统的关系型数据库操作有些不同。基于HBase表的实现是,首先打开一个Scanner实例(例如调用ScannerOpen()),返回一个id,然后再使用该id,调用ScannerGetList()方法(可以指定每次返回几条记录的变量nbRows的值),返回一个记录列表,反复调用该ScannerGetList()方法,直到此次没有结果返回为止。后面会通过测试用例来实际体会。
现在,我们基于上抽象出来的客户端操作接口,给出一个基本的实现,代码如下所示:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HbaseThrift.HBase.Thrift { class HBaseThriftClient : AbstractHBaseThriftService { public HBaseThriftClient() : this("localhost", 9090) { } public HBaseThriftClient(string host, int port) : base(host, port) { } public override List GetTables() { List tables = client.getTableNames(); List list = new List(); foreach(byte[] table in tables) { list.Add(Decode(table)); } return list; } public override void Update(string table, string rowKey, bool writeToWal, string fieldName, string fieldValue, Dictionary attributes) { byte[] tableName = Encode(table); byte[] row = Encode(rowKey); Dictionary encodedAttributes = EncodeAttributes(attributes); List mutations = new List(); Mutation mutation = new Mutation(); mutation.IsDelete = false; mutation.WriteToWAL = writeToWal; mutation.Column = Encode(fieldName); mutation.Value = Encode(fieldValue); mutations.Add(mutation); client.mutateRow(tableName, row, mutations, encodedAttributes); } public override void Update(string table, string rowKey, bool writeToWal, Dictionary fieldNameValues, Dictionary attributes) { byte[] tableName = Encode(table); byte[] row = Encode(rowKey); Dictionary encodedAttributes = EncodeAttributes(attributes); List mutations = new List(); foreach (KeyValuePair pair in fieldNameValues) { Mutation mutation = new Mutation(); mutation.IsDelete = false; mutation.WriteToWAL = writeToWal; mutation.Column = Encode(pair.Key); mutation.Value = Encode(pair.Value); mutations.Add(mutation); } client.mutateRow(tableName, row, mutations, encodedAttributes); } public override void DeleteCell(string table, string rowKey, bool writeToWal, string column, Dictionary attributes) { byte[] tableName = Encode(table); byte[] row = Encode(rowKey); Dictionary encodedAttributes = EncodeAttributes(attributes); List mutations = new List(); Mutation mutation = new Mutation(); mutation.IsDelete = true; mutation.WriteToWAL = writeToWal; mutation.Column = Encode(column); mutations.Add(mutation); client.mutateRow(tableName, row, mutations, encodedAttributes); } public override void DeleteCells(string table, string rowKey, bool writeToWal, List columns, Dictionary attributes) { byte[] tableName = Encode(table); byte[] row = Encode(rowKey); Dictionary encodedAttributes = EncodeAttributes(attributes); List mutations = new List(); foreach (string column in columns) { Mutation mutation = new Mutation(); mutation.IsDelete = true; mutation.WriteToWAL = writeToWal; mutation.Column = Encode(column); mutations.Add(mutation); } client.mutateRow(tableName, row, mutations, encodedAttributes); } public override void DeleteRow(string table, string rowKey, Dictionary attributes) { byte[] tableName = Encode(table); byte[] row = Encode(rowKey); Dictionary encodedAttributes = EncodeAttributes(attributes); client.deleteAllRow(tableName, row, encodedAttributes); } public override int ScannerOpen(string table, string startRow, List columns, Dictionary attributes) { byte[] tableName = Encode(table); byte[] start = Encode(startRow); List encodedColumns = EncodeStringList(columns); Dictionary encodedAttributes = EncodeAttributes(attributes); return client.scannerOpen(tableName, start, encodedColumns, encodedAttributes); } public override int ScannerOpen(string table, string startRow, string stopRow, List columns, Dictionary attributes) { byte[] tableName = Encode(table); byte[] start = Encode(startRow); byte[] stop = Encode(stopRow); List encodedColumns = EncodeStringList(columns); Dictionary encodedAttributes = EncodeAttributes(attributes); return client.scannerOpenWithStop(tableName, start, stop, encodedColumns, encodedAttributes); } public override int ScannerOpenWithPrefix(string table, string startAndPrefix, List columns, Dictionary attributes) { byte[] tableName = Encode(table); byte[] prefix = Encode(startAndPrefix); List encodedColumns = EncodeStringList(columns); Dictionary encodedAttributes = EncodeAttributes(attributes); return client.scannerOpenWithPrefix(tableName, prefix, encodedColumns, encodedAttributes); } public override int ScannerOpenTs(string table, string startRow, List columns, long timestamp, Dictionary attributes) { byte[] tableName = Encode(table); byte[] start = Encode(startRow); List encodedColumns = EncodeStringList(columns); Dictionary encodedAttributes = EncodeAttributes(attributes); return client.scannerOpenTs(tableName, start, encodedColumns, timestamp, encodedAttributes); } public override int ScannerOpenTs(string table, string startRow, string stopRow, List columns, long timestamp, Dictionary attributes) { byte[] tableName = Encode(table); byte[] start = Encode(startRow); byte[] stop = Encode(stopRow); List encodedColumns = EncodeStringList(columns); Dictionary encodedAttributes = EncodeAttributes(attributes); return client.scannerOpenWithStopTs(tableName, start, stop, encodedColumns, timestamp, encodedAttributes); } public override List ScannerGetList(int id, int nbRows) { return client.scannerGetList(id, nbRows); } public override List ScannerGet(int id) { return client.scannerGet(id); } public override List GetRow(string table, string row, Dictionary attributes) { byte[] tableName = Encode(table); byte[] startRow = Encode(row); Dictionary encodedAttributes = EncodeAttributes(attributes); return client.getRow(tableName, startRow, encodedAttributes); } public override List GetRows(string table, List rows, Dictionary attributes) { byte[] tableName = Encode(table); List encodedRows = EncodeStringList(rows); Dictionary encodedAttributes = EncodeAttributes(attributes); return client.getRows(tableName, encodedRows, encodedAttributes); } public override List GetRowsWithColumns(string table, List rows, List columns, Dictionary attributes) { byte[] tableName = Encode(table); List encodedRows = EncodeStringList(rows); List encodedColumns = EncodeStringList(columns); Dictionary encodedAttributes = EncodeAttributes(attributes); return client.getRowsWithColumns(tableName, encodedRows, encodedColumns, encodedAttributes); } public override void ScannerClose(int id) { client.scannerClose(id); } public override void IterateResults(TRowResult result) { foreach (KeyValuePair pair in result.Columns) { Console.WriteLine("\tCol=" + Decode(pair.Key) + ", Value=" + Decode(pair.Value.Value)); } } private String Decode(byte[] bs) { return UTF8Encoding.Default.GetString(bs); } private byte[] Encode(String str) { return UTF8Encoding.Default.GetBytes(str); } private Dictionary EncodeAttributes(Dictionary attributes) { Dictionary encodedAttributes = new Dictionary(); foreach (KeyValuePair pair in attributes) { encodedAttributes.Add(Encode(pair.Key), Encode(pair.Value)); } return encodedAttributes; } private List EncodeStringList(List strings) { List list = new List(); if (strings != null) { foreach (String str in strings) { list.Add(Encode(str)); } } return list; } } }
上面代码,给出了基本的实现,接着我们给出测试用例,调用我们实现的客户端操作,与HBase表进行交互。实现的测试用例类如下所示:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HbaseThrift.HBase.Thrift { class Test { private readonly AbstractHBaseThriftService client; public Test(String host, int port) { client = new HBaseThriftClient(host, port); } public Test() : this("master", 9090) { } static String RandomlyBirthday() { Random r = new Random(); int year = 1900 + r.Next(100); int month = 1 + r.Next(12); int date = 1 + r.Next(30); return year + "-" + month.ToString().PadLeft(2, '0') + "-" + date.ToString().PadLeft(2, '0'); } static String RandomlyGender() { Random r = new Random(); int flag = r.Next(2); return flag == 0 ? "M" : "F"; } static String RandomlyUserType() { Random r = new Random(); int flag = 1 + r.Next(10); return flag.ToString(); } public void Close() { client.Close(); } public void CaseForUpdate() { bool writeToWal = false; Dictionary attributes = new Dictionary(0); string table = SetTable(); // put kv pairs for (int i = 0; i <p>上面的测试可以实现操作Hbase表数据。另外,在生成的Thrift客户端代码中,Iface中给出了全部的服务接口,可以根据需要来选择,客户端Client实现了与Thrift交互的一些逻辑的处理,通过该类对象可以代理HBase提供的Thrift服务。</p> <p><strong>参考链接</strong></p>
- http://wiki.apache.org/hadoop/Hbase/ThriftApi
- http://svn.apache.org/viewvc/hbase/trunk/hbase-server/src/main/resources/org/apache/hadoop/hbase/thrift/Hbase.thrift?view=markup
- http://www.cnblogs.com/panfeng412/archive/2012/11/11/hbase-thrift-api-common-issues-summary.html
- https://github.com/simplegeo/hadoop-hbase/blob/master/src/examples/thrift/DemoClient.java
- http://thrift.apache.org/tutorial/java/
原文地址:基于C#+Thrift操作HBase实践, 感谢原作者分享。

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PyCharm은 매우 인기 있는 Python 통합 개발 환경(IDE)으로 Python 개발을 더욱 효율적이고 편리하게 만들어주는 다양한 기능과 도구를 제공합니다. 이 기사에서는 PyCharm의 기본 작동 방법을 소개하고 독자가 도구 작동을 빠르게 시작하고 능숙하게 사용할 수 있도록 구체적인 코드 예제를 제공합니다. 1. PyCharm 다운로드 및 설치 먼저 PyCharm 공식 웹사이트(https://www.jetbrains.com/pyc)로 이동해야 합니다.

LinuxDeploy 작업 단계 및 주의 사항 LinuxDeploy는 사용자가 Android 장치에 다양한 Linux 배포판을 신속하게 배포하여 모바일 장치에서 완전한 Linux 시스템을 경험할 수 있도록 도와주는 강력한 도구입니다. 이 기사에서는 LinuxDeploy의 작동 단계와 주의 사항을 자세히 소개하고 독자가 이 도구를 더 잘 사용할 수 있도록 구체적인 코드 예제를 제공합니다. 작업 단계: Linux 설치배포: 먼저 설치

이메일 관리자 애플리케이션인 Microsoft Outlook을 사용하면 이벤트와 약속을 예약할 수 있습니다. 이를 통해 Outlook 응용 프로그램에서 이러한 활동(이벤트라고도 함)을 생성, 관리 및 추적할 수 있는 도구를 제공하여 체계적으로 정리할 수 있습니다. 그러나 때로는 원치 않는 이벤트가 Outlook의 일정에 추가되어 사용자에게 혼란을 주고 일정에 스팸을 보내는 경우가 있습니다. 이 문서에서는 Outlook이 내 일정에 이벤트를 자동으로 추가하지 못하도록 방지하는 데 도움이 되는 다양한 시나리오와 단계를 살펴보겠습니다. Outlook 이벤트 – 간략한 개요 Outlook 이벤트는 다양한 용도로 사용되며 다음과 같은 유용한 기능을 많이 가지고 있습니다. 일정 통합: Outlook에서

아마도 많은 사용자들이 집에 사용하지 않는 컴퓨터가 여러 대 있고, 오랫동안 사용하지 않았기 때문에 시동 암호를 완전히 잊어버렸기 때문에 암호를 잊어버린 경우 어떻게 해야 하는지 알고 싶습니까? 그럼 함께 살펴볼까요? win10 부팅 암호를 입력하는 데 F2 키를 잊어버린 경우 어떻게 해야 합니까? 1. 컴퓨터의 전원 버튼을 누른 다음 컴퓨터를 켤 때 F2 키를 누릅니다(컴퓨터 브랜드마다 BIOS에 들어가는 버튼이 다릅니다). 2. BIOS 인터페이스에서 보안 옵션을 찾으세요(컴퓨터 브랜드에 따라 위치가 다를 수 있음). 일반적으로 상단의 설정 메뉴에 있습니다. 3. 그런 다음 SupervisorPassword 옵션을 찾아 클릭합니다. 4. 이때 사용자는 자신의 비밀번호를 볼 수 있으며 동시에 옆에 있는 활성화를 찾아 Dis로 전환합니다.

스마트폰이 대중화되면서 스크린샷 기능은 일상적인 휴대폰 사용에 필수적인 기술 중 하나로 자리 잡았습니다. Huawei의 주력 휴대폰 중 하나인 Huawei Mate60Pro의 스크린샷 기능은 자연스럽게 사용자로부터 많은 관심을 끌었습니다. 오늘은 모두가 더욱 편리하게 스크린샷을 찍을 수 있도록 Huawei Mate60Pro 휴대폰의 스크린샷 작업 단계를 공유하겠습니다. 우선, Huawei Mate60Pro 휴대폰은 다양한 스크린샷 방법을 제공하며, 개인 습관에 따라 자신에게 맞는 방법을 선택할 수 있습니다. 다음은 일반적으로 사용되는 몇 가지 차단에 대한 자세한 소개입니다.

Dreamweaver CMS 스테이션 그룹 실습 공유 최근 몇 년간 인터넷의 급속한 발전으로 인해 웹사이트 구축이 점점 더 중요해지고 있습니다. 여러 웹사이트를 구축할 때 사이트 그룹 기술은 매우 효과적인 방법이 되었습니다. 많은 웹 사이트 구축 도구 중에서 DreamWeaver CMS는 유연성과 사용 용이성으로 인해 많은 웹 사이트 애호가들의 첫 번째 선택이 되었습니다. 이 기사에서는 Dreamweaver CMS 스테이션 그룹에 대한 몇 가지 실제 경험과 일부 특정 코드 예제를 공유하여 스테이션 그룹 기술을 탐색하는 독자에게 도움이 되기를 바랍니다. 1. Dreamweaver CMS 스테이션 그룹이란 무엇입니까? 드림위버 CMS

PHP 코딩 방법: Goto 문에 대한 대안 사용 거부 최근 몇 년간 프로그래밍 언어의 지속적인 업데이트와 반복으로 인해 프로그래머는 코딩 사양과 모범 사례에 더 많은 관심을 기울이기 시작했습니다. PHP 프로그래밍에서 goto 문은 오랫동안 제어 흐름 문으로 존재해 왔지만, 실제 응용에서는 코드의 가독성과 유지 관리성이 떨어지는 경우가 많습니다. 이 기사에서는 개발자가 goto 문 사용을 거부하고 코드 품질을 향상시키는 데 도움이 되는 몇 가지 대안을 공유합니다. 1. goto 문 사용을 거부하는 이유는 무엇입니까? 먼저 그 이유를 생각해 보자.

Golang은 웹 서비스 및 애플리케이션을 구축하는 데 널리 사용되는 강력하고 효율적인 프로그래밍 언어입니다. 네트워크 서비스에서 트래픽 관리는 네트워크상의 데이터 전송을 제어 및 최적화하고 서비스의 안정성과 성능을 보장하는 데 도움이 되는 중요한 부분입니다. 이 기사에서는 Golang을 사용한 트래픽 관리 모범 사례를 소개하고 구체적인 코드 예제를 제공합니다. 1. 기본 트래픽 관리를 위해 Golang의 넷 패키지를 사용합니다. Golang의 넷 패키지는 네트워크 데이터를 처리하는 방법을 제공합니다.
