文档首页/
云数据库 GeminiDB/
GeminiDB HBase接口/
用户指南/
实例连接及管理/
程序代码连接GeminiDB HBase接口实例/
通过Java连接GeminiDB HBase接口实例
更新时间:2025-08-04 GMT+08:00
通过Java连接GeminiDB HBase接口实例
本章节主要介绍使用Java语言连接GeminiDB HBase接口实例的基本操作。
前提条件
- 已成功创建GeminiDB HBase接口实例,且实例状态正常。创建GeminiDB HBase接口实例的方法请参见快速了解GeminiDB HBase接口。
- 获取GeminiDB HBase接口实例的开放的内网IP地址、端口。
内网IP地址和端口的获取方法请参见查看实例IP地址。
- 登录弹性云服务器,具体操作请参见《弹性云服务器快速入门》中“登录弹性云服务器”。
- 请添加以下Maven依赖到您项目中的pom.xml。如果使用1.X版本的客户端,将会出现兼容性问题导致读写失败,不建议使用。 建议使用hbase-client 2.2.3及以上的依赖版本,其中SSL功能仅在hbase-client 2.6.0以上版本支持。
<dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>2.6.1</version> </dependency>
- 编辑连接GeminiDB HBase接口实例的代码,将代码中的"your_hbase_instance_quorum" 替换为集群IP地址,"your_user_name"替换为您创建集群时设置的用户名(默认为rwuser),替换"your_password"为您创建集群时设置的密码。同时运行该代码需要您在实例中已经有创建好的HBase表,并且替换相应表名到代码中的 "your_table_name"处。
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; public class HBaseExample { public static void main(String[] args) throws IOException { // 创建配置对象并设置Hbase连接参数 Configuration config = HBaseConfiguration.create(); config.set("hbase.zookeeper.quorum", "your_hbase_instance_quorum"); config.set("hbase.zookeeper.property.clientPort", "2181"); // 填写用户名和密码 UserGroupInformation ugi = UserGroupInformation.createProxyUser("your_user_name", UserGroupInformation.createRemoteUser("your_password")); // 建立与Hbase实例的连接 Connection connection = ConnectionFactory.createConnection(config, User.create(ugi)); try { // 获取表对象 TableName tableName = TableName.valueOf("your_table_name"); Table table = connection.getTable(tableName); // 插入数据 Put put = new Put(Bytes.toBytes("row_key")); put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("col"), Bytes.toBytes("value")); table.put(put); // 获取单行数据 Get get = new Get(Bytes.toBytes("row_key")); Result result = table.get(get); byte[] value = result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("col")); System.out.println("Success: " + Bytes.toString(value)); } finally { // 关闭连接 connection.close(); } } }
- 运行示例代码,确认结果是否正常。样例输出为 "Success: value"