在重写以前的代码的时候,换了新版本的hbase,导致出现了很多问题,在此记录一下,新旧版本创建HBaseAdmin的方式
创建的HBaseAdmin里面传入的是configuration。
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
public class HbaseDemoTest {
// 声明静态配置
static Configuration conf = null;
private static final String ZK_CONNECT_STR = "hadoop01:2181,hadoop02:2181";
static {
conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", ZK_CONNECT_STR);
}
/*
* 创建表
* @tableName 表名
* @family 列簇列表
*/
public static void creatTable(String tableName, String[] family) throws Exception {
HBaseAdmin admin = new HBaseAdmin(conf);
HTableDescriptor desc = new HTableDescriptor(tableName);
for (int i = 0; i < family.length; i++) {
desc.addFamily(new HColumnDescriptor(family[i]));
}
if (admin.tableExists(tableName)) {
System.out.println("table Exists!");
System.exit(0);
} else {
admin.createTable(desc);
System.out.println("create table Success!");
}
}
}
目前使用的版本是2.3.2的hbase。在创建HBaseAdmin的时候需要借用链接
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
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.HBaseAdmin;
import java.io.IOException;
/**
* @version 1.0
* @date 2020/6/12 11:50
*/
public class HbaseUtils {
HBaseAdmin hBaseAdmin = null;
Connection connection = null;
Configuration configuration = null;
private HbaseUtils() {
configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.quorum", "hadoop001:2181");
try {
connection = ConnectionFactory.createConnection(configuration);
hBaseAdmin = (HBaseAdmin) connection.getAdmin();
} catch (IOException e) {
e.printStackTrace();
}
}
private static HbaseUtils instance = null;
public static synchronized HbaseUtils getInstance(){
if (instance == null){
instance = new HbaseUtils();
}
return instance;
}
public void createTable(String tableName,String[]family) throws IOException {
HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
for(String f: family){
tableDescriptor.addFamily(new HColumnDescriptor(f));
}
// 创建表
hBaseAdmin.createTable(tableDescriptor );
System.out.println("创建" + tableName + "表成功");
}
}