Java访问HBase的方法,网上都能找到,我使用的是文档中的读取hbase-site.xml文件的形式,当然也可以使用在yml文件中配置的形式。
在使用Java操作HBase时,和常规操作数据库不一样,在此汇总了些常用的方法!(由于我使用的版本是2.2.6,用新版本的替代一些过时的方法和类,如果使用的是低版本,有些方法和类可能稍有不同,可参照2.2.6版本源码中进行修改,本文中会给出例子让我们更好的去实现)
一、整合HBase
首先导包
免手打(就是这么懒)
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>2.2.6</version>
</dependency>
导入配置文件hbase-site.xml文件,这个文件所在路径是HBase安装目录下的conf文件夹内
从上面的文件夹下取出hbase-site.xml文件,导入到我们项目中的resource下,如图
hosts文件配置
首先打开上一步导入的hbase-site.xml文件
如果我们hosts文件已经配置了hadoop1,hadoop2,hadoop3对应的映射地址,那这一步可以忽略,如果没有配置,则需要配置hosts文件,
进入C:\Windows\System32\drivers\etc,把hosts文件复制出来(直接修改无法保存,用修改后文件进行覆盖的方法)
打开复制出来的hosts文件
(注意:每个节点与服务器地址一定要对应)
保存后,把hosts文件拷贝至C:\Windows\System32\drivers\etc覆盖原来的即可
写配置类
config代码
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Create by squeen.hao
* Date 2021/2/19 15:10
* Description
*/
@Configuration
public class HBaseConfig {
@Bean
public HBaseService getHBaseService(){
//执行此步时,会去resources目录下找相应的配置文件,例如hbase-site.xml
org.apache.hadoop.conf.Configuration configuration = HBaseConfiguration.create();
return new HBaseService(configuration);
}
}
实现类
二、常用的Java操作HBase方法
package com.jinkosolar.jinkoextend.service;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;
/**
* Create by squeen.hao
* Date 2021/2/19 15:11
* Description
*/
public class HBaseService {
private Logger log = LoggerFactory.getLogger(HBaseService.class);
private Admin admin = null;
private Connection connection = null;
public HBaseService (Configuration conf) {
try {
connection = ConnectionFactory.createConnection(conf);
admin = connection.getAdmin();
log.info("----------------admin: " + admin);
} catch (IOException e) {
e.printStackTrace();
log.error("获取HBase连接失败!");
}
}
/**
* 创建表并创建列族
* @param tableName
* @param columnFamily
* @return
*/
public boolean creatTable(String tableName, List<String> columnFamily) {
try {
//列族column family
List<ColumnFamilyDescriptor> cfDesc = new ArrayList<>(columnFamily.size());
columnFamily.forEach(cf -> {
cfDesc.add(ColumnFamilyDescriptorBuilder.newBuilder(
Bytes.toBytes(cf)).build());
});
//表 table
TableDescriptor tableDesc = TableDescriptorBuilder
.newBuilder(TableName.valueOf(tableName))
.setColumnFamilies(cfDesc).build();
if (admin.tableExists(TableName.valueOf(tableName))) {
log.info("创建表失败,表[" + tableName + "]已存在,table Exists!");
} else {
admin.createTable(tableDesc);
log.debug("create table Success!");
}
} catch (