本文共 2576 字,大约阅读时间需要 8 分钟。
HBase作为一个面向列族的数据库,和一般的数据库不同,没法用JDBC封装的那套util,便重新封装了个HBase自己的util供项目使用。
注意修改成自己的版本,可以去https://mvnrepository.com/artifact/org.apache.hbase/hbase-client和https://mvnrepository.com/artifact/org.apache.hbase/hbase-server选择版本。
org.apache.hbase hbase-server 1.4.5 org.apache.hbase hbase-client 1.4.5
声明一些私有属性
private Configuration hbaseConf; private Connection hbaseConn; private HBaseAdmin admin;
需要将这些文件放到resources,直接用集群文件中的就行;当然也可以手写但是太过麻烦,毕竟有hadoop、zookpeer、hbase三者的信息。
public HBaseUtil() { hbaseConf = HBaseConfiguration.create(); try { hbaseConn = ConnectionFactory.createConnection(); admin = (HBaseAdmin) hbaseConn.getAdmin(); System.out.println("连接上了吗?"+!hbaseConn.isClosed()); } catch (IOException e) { e.printStackTrace(); } }
public boolean isExist(String tableNameStr){ TableName tableName = TableName.valueOf(tableNameStr); boolean flag = false; try { flag = admin.tableExists(tableName); } catch (IOException e) { e.printStackTrace(); } return flag; }
public void createTable(String tableNameStr,String[] familys){ if(this.isExist(tableNameStr)){ System.out.println("表格已经存在了"); return; } TableName tableName = TableName.valueOf(tableNameStr); //表描述 HTableDescriptor table = new HTableDescriptor(tableName); //列族描述 for(String familyStr:familys){ HColumnDescriptor family = new HColumnDescriptor(familyStr); table.addFamily(family); } try { admin.createTable(table); } catch (IOException e) { e.printStackTrace(); } }
public void dropTable(String tableName) { try { admin.disableTable(tableName); admin.deleteTable(tableName); } catch (MasterNotRunningException e) { e.printStackTrace(); } catch (ZooKeeperConnectionException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void putData(String tableNameStr,Put put){ TableName tableName = TableName.valueOf(tableNameStr); Table table; try { table = hbaseConn.getTable(tableName); table.put(put); } catch (IOException e) { e.printStackTrace(); } }
public void putData(String tableNameStr,ListputList){ TableName tableName = TableName.valueOf(tableNameStr); Table table; try { table = hbaseConn.getTable(tableName); table.put(putList); } catch (IOException e) { e.printStackTrace(); } }
转载地址:http://rejzk.baihongyu.com/