本文主要介绍如何使用JavaClient访问HBase。
访问准备
需要在相同的Region内准备一台ECS。如果已经有ECS了那么请继续下一步。如果还没有,您可以在ECS的购买页面上购买一台按量的ECS进行测试。设置请参考这里。
也可以采取公网访问的方式:公网访问方案。
使用Client读写HBase
云HBase企业标准版可以直接使用社区开源版客户端,也可以使用阿里定制的HBase客户端访问,下载和依赖客户端的方式请参见客户端下载。如果是公网访问必须使用阿里提供的客户端。
如果您的运行环境上并没有HBase的client运行需要的JAR包,请在maven中添加如下的shade配置,把所有hbase-client的依赖都打到最终的JAR包中。
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
获取集群的ZK连接地址。
登录Hbase控制台集群详情页面,在连接信息部分查看ZK连接地址,可以看到类似如下的ZooKeeper的连接地址。HBase增强版集群请参见HBase Java API 访问。
hb-bp1f5xxxx48a0r17i-001.hbase.rds.aliyuncs.com:2181
hb-bp1f5xxxx48a0r17i-002.hbase.rds.aliyuncs.com:2181
hb-bp1f5xxxx48a0r17i-003.hbase.rds.aliyuncs.com:2181
配置ZK地址,连接集群。
将集群的ZK地址替换代码中的ZK地址,就可以使用如下的示例代码来进行Hbase集群的访问了。 例子中展示了创建表、写入数据、读取数据 三种场景。
private static final String TABLE_NAME = "mytable";
private static final String CF_DEFAULT = "cf";
public static final byte[] QUALIFIER = "col1".getBytes();
private static final byte[] ROWKEY = "rowkey1".getBytes();
public static void main(String[] args) {
Configuration config = HBaseConfiguration.create();
String zkAddress = "hb-bp1f5xxxx48a0r17i-001.hbase.rds.aliyuncs.com:2181,hb-bp1f5xxxx48a0r17i-002.hbase.rds.aliyuncs.com:2181,hb-bp1f5xxxx48a0r17i-003.hbase.rds.aliyuncs.com:2181";
config.set(HConstants.ZOOKEEPER_QUORUM, zkAddress);
Connection connection = null;
try {
connection = ConnectionFactory.createConnection(config);
HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(TABLE_NAME));
tableDescriptor.addFamily(new HColumnDescriptor(CF_DEFAULT));
System.out.print("Creating table. ");
Admin admin = connection.getAdmin();
admin.createTable(tableDescriptor);
System.out.println(" Done.");
Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
try {
Put put = new Put(ROWKEY);
put.addColumn(CF_DEFAULT.getBytes(), QUALIFIER, "this is value".getBytes());
table.put(put);
Get get = new Get(ROWKEY);
Result r = table.get(get);
byte[] b = r.getValue(CF_DEFAULT.getBytes(), QUALIFIER); // returns current version of value
System.out.println(new String(b));
} finally {
if (table != null) table.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
代码样例
您也可以在这里下载我们提供的Java代码工程,替换其中的ZooKeeper变量部分后使用。