您可以通过以下两种方式,来配置访问HBase增强版的客户端参数。
使用前须知
此安装方法只适用于alihbase-connector 1.0.8/2.0.8以及之前的版本。如果版本号大于1.0.8/2.0.8,请参见使用Java API访问增强版集群。
前提条件
- 已完成JAVA SDK 安装。
- 已获取集群的连接地址。
配置客户端参数
方式一:配置文件
hbase-site.xml 中增加下列配置项:
<configuration>
<property>
<name>hbase.client.connection.impl</name>
<value>com.alibaba.hbase.client.AliHBaseUEConnection</value>
</property>
<!--
集群的连接地址(注意公网地址和VPC内网地址)
-->
<property>
<name>hbase.client.endpoint</name>
<value>HOST:PORT</value>
</property>
<!--
设置用户名和密码,默认均为root,可根据实际情况调整
-->
<property>
<name>hbase.client.username</name>
<value>testuser</value>
</property>
<property>
<name>hbase.client.password</name>
<value>password</value>
</property>
</configuration>
方式二:代码
通过代码Create Configuration,然后增加相关配置。
// 新建一个Configuration
Configuration conf = HBaseConfiguration.create();
// 将HBase底层Connection实现替换成HBase增强版专用的AliHBaseUEConnection
conf.set("hbase.client.connection.impl", AliHBaseUEConnection.class.getName());
// 集群的连接地址(注意公网地址和VPC内网地址)
conf.set("hbase.client.endpoint", "HOST:PORT");
// 设置用户名和密码,默认均为root,可根据实际情况调整
conf.set("hbase.client.username", "testuser")
conf.set("hbase.client.password", "password")
说明 访问HBase增强版不需要配置zookeeper的地址参数(hbase.zookeeper.quorum)。
创建连接
通过配置conf创建Connection,然后访问HBase。
// 创建 HBase连接,在程序生命周期内只需创建一次,该连接线程安全,可以共享给所有线程使用。
// 在程序结束后,需要将Connection对象关闭,否则会造成连接泄露。
// 也可以采用try finally方式防止泄露
Connection connection = ConnectionFactory.createConnection(conf);
使用API
建立完连接后,即可使用Java API访问HBase增强版集群。下面提供一些简单的Java示例。
DDL操作
try (Admin admin = connection.getAdmin()){
// 建表
HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("tablename"));
htd.addFamily(new HColumnDescriptor(Bytes.toBytes("family")));
// 创建一个只有一个分区的表
// 在生产上建表时建议根据数据特点预先分区
admin.createTable(htd);
// disable 表
admin.disableTable(TableName.valueOf("tablename"));
// truncate 表
admin.truncateTable(TableName.valueOf("tablename"), true);
// 删除表
admin.deleteTable(TableName.valueOf("tablename"));
}
DML操作
//Table 为非线程安全对象,每个线程在对Table操作时,都必须从Connection中获取相应的Table对象
try (Table table = connection.getTable(TableName.valueOf("tablename"))) {
// 插入数据
Put put = new Put(Bytes.toBytes("row"));
put.addColumn(Bytes.toBytes("family"), Bytes.toBytes("qualifier"), Bytes.toBytes("value"));
table.put(put);
// 单行读取
Get get = new Get(Bytes.toBytes("row"));
Result res = table.get(get);
// 删除一行数据
Delete delete = new Delete(Bytes.toBytes("row"));
table.delete(delete);
// scan 范围数据
Scan scan = new Scan(Bytes.toBytes("startRow"), Bytes.toBytes("endRow"));
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
// 处理查询结果result
// ...
}
scanner.close();
}