首先通过链接 http://archive.apache.org/dist/thrift/0.12.0/thrift-0.12.0.tar.gz
下载 thrift 0.12.0 版本的 tar 包
通过 visual studio IDE 创建一个 .net framework 项目的类库解决方案

thrift-0.12.0\thrift-0.12.0\lib\csharp\src
下,可以看到我们需要的文件 下载 hbase 的 thrift 定义文件。
下载完成后,打开命令行,跳转到对应的目录下,执行 thrift-0.12.0.exe --gen csharp hbase.thrift,这个命令会生成一个 gen-csharp 的文件夹
\bin\Debug
下能找到)
生成 aaa.dll 和 bbb.dll 之后,便能够编写简单的 demo 进行访问了。还是通过 visual studio 新建一个 .net framework 的控制台应用,在引用处,添加 aaa.dll 和 bbb.dll。下面我给出简单的 demo 代码,大致做了以下几件事:
- 初始化客户端
- 创建 namespace
- 创建 table
- put 一条数据
- get 一条数据并且打印出来
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Thrift.Protocol;
using Thrift.Transport;
namespace hbaseDemo
{
class Program
{
static void Main(string[] args)
{
try
{
Uri uri = new Uri("http://ld-bp1u7jrc0818gtyql-proxy-hbaseue-pub.hbaseue.rds.aliyuncs.com:9190");
THttpClient transport = new THttpClient(uri);
IDictionary<string, string> header = transport.CustomHeaders;
header.Add("ACCESSKEYID", "root");
header.Add("ACCESSSIGNATURE", "root");
TProtocol tProtocol = new TBinaryProtocol(transport);
var client = new THBaseService.Client(tProtocol);
transport.Open();
String ns = "guchi5";
client.createNamespace(new TNamespaceDescriptor(ns));
byte[] tableNameBytes = Encoding.UTF8.GetBytes("tablename");
byte[] familyByte = Encoding.UTF8.GetBytes("f");
TTableName tTableName = new TTableName(tableNameBytes);
tTableName.Ns = Encoding.UTF8.GetBytes(ns);
TTableDescriptor tTableDescriptor = new TTableDescriptor(tTableName);
List<TColumnFamilyDescriptor> columns = new List<TColumnFamilyDescriptor>();
columns.Add(new TColumnFamilyDescriptor(Encoding.UTF8.GetBytes("f")));
tTableDescriptor.Columns = columns;
client.createTable(tTableDescriptor, null);
byte[] rowByte = Encoding.UTF8.GetBytes("row");
List<TColumnValue> list = new List<TColumnValue>();
list.Add(new TColumnValue(familyByte, Encoding.UTF8.GetBytes("q1"), Encoding.UTF8.GetBytes("value-guchi")));
string namespaceAndTableName = ns + ":tablename";
byte[] namespaceAndTableNameBytes = Encoding.UTF8.GetBytes(namespaceAndTableName);
client.put(namespaceAndTableNameBytes, new TPut(rowByte, list));
TGet tget = new TGet(rowByte);
TResult result = client.get(namespaceAndTableNameBytes, tget);
Console.WriteLine("RowKey:\n{0}", Encoding.UTF8.GetString(result.Row));
//打印Qualifier和对应的Value
foreach (var k in result.ColumnValues)
{
Console.WriteLine("Family:Qualifier:" + "\n" + Encoding.UTF8.GetString(k.Qualifier));
Console.WriteLine("Value:" + Encoding.UTF8.GetString(k.Value));
}
Console.WriteLine("done");
} catch (Exception e)
{
System.Console.WriteLine(e);
}
}
}
}
运行上述代码能看到以下输出
需要注意以下 2 点:
- 替换代码中的 url 部分,换成你自己的实例对应的公网连接地址
- 参考文档,对你需要进行访问的实例开通白名单和公网访问地址 https://help.aliyun.com/document_detail/119565.html?spm=a2c4g.11186623.6.560.1de042ddV8UbdR