// 创建主程序类 public class HBaseDemo { HBaseAdmin hba = null; HTable htable = null; String tableName = "phone";
// 连接函数,连接HBase,待进行后续操作 @Before public void conn() throws MasterNotRunningException, ZooKeeperConnectionException, IOException{ Configuration conf = new Configuration(); conf.set("hbase.zookeeper.quorum", "node02,node03,node04"); hba = new HBaseAdmin(conf); htable = new HTable(conf, tableName); }
// 创建表函数 @Test public void createTable() throws IOException{ if (hba.tableExists(tableName)){ hba.disableTable(tableName); hba.deleteTable(tableName); }
HTableDescriptor desc = new HTableDescriptor(tableName.valueOf(tableName)); HColumnDescriptor cf = new HColumnDescriptor("cf"); cf.setBlockCacheEnabled(true); cf.setInMemory(true); desc.addFamily(cf); hba.createTable(desc); }
// 插入数据 @Test public void insertDB() throws RetriesExhaustedWithDetailsException, InterruptedIOException{ byte[] rk = "111".getBytes(); Put put = new Put(rk); put.add("cf".getBytes(), "name".getBytes(), "zhangsan".getBytes()); put.add("cf".getBytes(), "age".getBytes(), "10".getBytes()); put.add("cf".getBytes(), "sex".getBytes(), "m".getBytes()); htable.put(put); }
// 获取数据 @Test public void getDB() throws IOException{ Get get = new Get("111".getBytes()); get.addColumn("cf".getBytes(), "name".getBytes()); get.addColumn("cf".getBytes(), "age".getBytes()); Result result = htable.get(get); Cell cellName = result.getColumnLatestCell("cf".getBytes(), "name".getBytes()); Cell cellAge = result.getColumnLatestCell("cf".getBytes(), "age".getBytes()); byte[] name = CellUtil.cloneValue(cellName); byte[] age = CellUtil.cloneValue(cellAge); System.out.println("姓名:" + new String(name)); System.out.println("年龄:" + new String(age)); }
// 查询表中所有数据 @Test public void scanDB() throws IOException { Scan scan = new Scan(); ResultScanner result = htable.getScanner(scan); Iterator<Result> iterator = result.iterator(); while(iterator.hasNext()) { Result rs = iterator.next(); Cell cellName = rs.getColumnLatestCell("cf".getBytes(), "name".getBytes()); Cell cellAge = rs.getColumnLatestCell("cf".getBytes(), "age".getBytes()); Cell cellSex = rs.getColumnLatestCell("cf".getBytes(), "sex".getBytes());
System.out.println(new String(CellUtil.cloneValue(cellName))); System.out.println(new String(CellUtil.cloneValue(cellAge))); System.out.println(new String(CellUtil.cloneValue(cellSex))); } }
//关闭HBase连接 @After public void close(){ if (null != hba){ try{ hba.close(); }catch(IOException ex){ ex.printStackTrace(); } }
if (null != htable){ try{ htable.close(); }catch(IOException ex) { ex.printStackTrace(); } } } }
|
Hadoop应用实验: HBase Java API使用
最新推荐文章于 2022-05-24 16:12:22 发布