一、前言
上篇文章已经说到docker快速部署hbase,这里就不多讲了,直接说今天内容《java如何连接hbase》
二、创建项目
- 1.准备一个Maven项目
加入以下配置在pom文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>
- 2.编写代码
package com.teddy.util;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import java.io.IOException;
/**
* @program: hy_hbase
* @description: hbase连接
* @author: Mr.Teddy
* @create: 2020-08-27 10:06
**/
public class HbaseHelep {
static Configuration conf = null;
static Connection conn;
static {
conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum","myhbase");
conf.set("hbase.zookeeper.property.clientPort","2181");
try {
conn = ConnectionFactory.createConnection(conf);
} catch (IOException e){
FileLog.error("连接hbase失败",e);
e.printStackTrace();
}
}
/**
* 创建表
* @param tableName 表名
* @param familyNames 例族信息
*/
public static boolean createTable(String tableName, String[] familyNames) {
Admin admin = null;
try {
admin = conn.getAdmin();
TableName name = TableName.valueOf(tableName);
if (admin.tableExists(name)){
System.out.println("Table Exists!");
} else {
HTableDescriptor tableDescriptor = new HTableDescriptor(name);
// 添加例族信息
if (familyNames != null && familyNames.length > 0) {
for (String familyName : familyNames) {
tableDescriptor.addFamily(new HColumnDescriptor(familyName));
}
}
admin.createTable(tableDescriptor);
System.out.println("Table Create Success!");
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (admin != null) {
try {
admin.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
return false;
}
/**
* 删除表
* @param tableName 表名
* 一定要先禁用 在删除
*/
public static boolean deleteTable(String tableName) {
try {
Admin admin = conn.getAdmin();
TableName name = TableName.valueOf(tableName);
admin.disableTable(name); // 禁用表
admin.deleteTable(name); // 删除表
return true;
} catch (IOException e) {
FileLog.error("删除表异常失败", e);
e.printStackTrace();
}
return false;
}
三、代码执行效果
- 1.访问我们的 http://localhost:16010/master-status 页面查看
- 2.执行 createTable 建表接口
- 3.去网页查看表是否建立成功
- 3.验证删除表接口
- 查看是否清楚成功
四、重点注意
-
1.环境问题(host文件一定要配置)
-
2.端口问题
刚开始我遇到连接conn成功,但是只要去操作数据就出一个连接异常没后来发现他要请求16020端口 去检查你docker是否有映射
这个就去看上篇文章,有讲解的 docker快速部署hbase及基本操作命令
添加数据,删除数据请看下篇文章
😁 作者:Teddy (公众号:鸡仓故事汇)
ok!到这里就大功告成,小编(Teddy)在这里先感谢大家的到来。
虽然不是太详细,小编已经很努力,给小编来个一键三连(点赞,关注,收藏),小编会越来越努力。。。