Java连接HBase
1.添加依赖
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
<hbase-client.version>1.2.4</hbase-client.version>
<junit.version>4.13.1</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>${hbase-client.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
<version>${junit.version}</version>
</dependency>
</dependencies>
2.设计HBaseConnUtil类
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
/**
* Created by jixin on 18-2-25.
*/
public class HBaseConnUtil {
private static final HBaseConnUtil INSTANCE = new HBaseConnUtil();
private static Configuration configuration;
private static Connection connection;
private HBaseConnUtil() {
try {
if (configuration == null) {
configuration = HBaseConfiguration.create();
//configuration.set("hbase.zookeeper.quorum", "localhost:2181");
configuration.set("hbase.zookeeper.quorum", "192.168.2.177:2181");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private Connection getConnection() {
if (connection == null || connection.isClosed()) {
try {
connection = ConnectionFactory.createConnection(configuration);
} catch (Exception e) {
e.printStackTrace();
}
}
return connection;
}
public static Connection getHBaseConn() {
return INSTANCE.getConnection();
}
public static Table getTable(String tableName) throws IOException {
return INSTANCE.getConnection().getTable(TableName.valueOf(tableName));
}
public static void closeConn() {
if (connection != null) {
try {
connection.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
3.测试连接
@RunWith(SpringRunner.class)
@SpringBootTest
public class HBaseConnTest {
@Test
public void testGetConnection() {
Connection conn = HBaseConnUtil.getHBaseConn();
System.out.println(conn.isClosed());
HBaseConnUtil.closeConn();
System.out.println(conn.isClosed());
}
@Test
public void getTableTest() {
try {
Table table = HBaseConnUtil.getTable("person");
System.out.println(table.getName().getNameAsString());
table.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
运行时如果报以下错误:
java.io.IOException: Could not locate executable C:\hadoop\bin\winutils.exe in the Hadoop binaries.
这是因为在win10上没有hadoop的运行环境,将 winutils 中的 hadoop.dll 文件 和 winutils.exe 文件 拷贝到 C:\Windows\System32 目录下,然后重启电脑即可解决问题。
百度网盘链接: 链接:https://pan.baidu.com/s/1RVpmbtjuQL3lbAEYfjr2EA 提取码:1234