今天完成了HBase的配置,实现了通过javaweb来操作HBase数据库,此外决定重构系统原型,使用Bootstrap开发自己的UI模型,进行了主页的简单布局设置。
package utils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; public class HBaseUtils { public static Configuration configuration; public static Connection connection; public static Admin admin; //建立连接 public static void init(){ //configuration= new Configuration(); configuration = HBaseConfiguration.create(); configuration.set("hbase.rootdir","hdfs://note1:8020/hbase"); configuration.set("hbase.zookeeper.quorum","note1,note2,note3"); configuration.set("hbase.zookeeper.property.dataDir","/export/server/zookeeper-3.4.9/zkdatas"); try{ connection = ConnectionFactory.createConnection(configuration); admin = connection.getAdmin(); }catch (IOException e) { e.printStackTrace(); } } //关闭连接 public static void close() { try{ if(admin != null) { admin.close(); } if(null != connection) { connection.close(); } }catch (IOException e) { e.printStackTrace(); } } //创建表 public static void createTable(String myTableName,String[] colFamily) throws IOException { TableName tableName=TableName.valueOf(myTableName); if (admin.tableExists(tableName)){ System.out.println("表已经存在"); return; }else{ HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName); for(String str: colFamily) { HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(str); hTableDescriptor.addFamily(hColumnDescriptor); } admin.createTable(hTableDescriptor); } } //插入数据 public static void insertData(String tableName,String rowKey,String colFamily,String col,String val)throws IOException { Table table = connection.getTable(TableName.valueOf(tableName)); Put put = new Put(Bytes.toBytes(rowKey)); put.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col), Bytes.toBytes(val)); table.put(put); table.close(); } //浏览数据 public static void getData(String tableName,String rowKey,String colFamily,String col)throws IOException{ Table table = connection.getTable(TableName.valueOf(tableName)); Get get = new Get(Bytes.toBytes(rowKey)); get.addColumn(Bytes.toBytes(colFamily),Bytes.toBytes(col)); //获取的result数据是结果集,还需要格式化输出想要的数据才行 Result result = table.get(get); System.out.println(new String(result.getValue(colFamily.getBytes(),col==null?null:col.getBytes()))); table.close(); } }
上面是操作HBase的核心代码