Idea获取HBase连接
当我们搭建好HBase集群后,使用shell操作不是很方便,此时我们可以考虑使用API来操作HBase.
根据官网的API,获取HBase连接,跟其他大数据框架API操作类似.
- 获取连接
- 进行业务操作
- 关闭连接
具体步骤
- 在pom.xml中添加依赖
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>2.5.1</version>
</dependency>
- 利用ConnectionFactory获取连接
// 声明一个静态属性
public static Connection connection;
static {
try {
connection = ConnectionFactory.createConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
按住Ctrl + 鼠标左键进入ConnectionFactory中我们会发现,在ConnectionFactory调用createConnection()方法时,默认加载了两个xml文件
hbase-default.xml和hbase-site.xml,我们一般使用后者进行配置
在resourse目录下创建配置文件hbase-site.xml,配置我们获取连接的服务
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
<name>hbase.zookeeper.quorum</name>
<value>192.168.10.102,192.168.10.103</value>
</property>
</configuration>
最后获取并关闭连接
public static void main(String[] args) throws IOException {
// 获取连接
System.out.println(HBaseConnection.connection);
// 关闭连接
HBaseConnection.close();
}
// 关闭连接
public static void close() throws IOException {
if (connection != null) {
connection.close();
}
}
测试
成功获取到连接
总结
ConnectionFactory默认读取hbase-site.xml中的配置,无需在调用createConnection()传入Configuration.