写MOB表
功能简介
HBase MOB数据的写入与普通HBase数据的写入没有什么区别,对客户来说是透明的。为了使用HBase MOB功能需要在“hbase-site.xml”中添加HBase MOB相关的配置项,具体请参见https://hbase.apache.org/book.html#hbase_mob,除此之外还需要在指定column family上开启MOB功能,样例代码如下:
代码样例
以下代码片段在com.huawei.bigdata.hbase.examples包的“HBaseExample”类的testCreateMOBTable方法中
public void testCreateMOBTable() { LOG.info("Entering testCreateMOBTable."); Admin admin = null; try { // Create Admin instance admin = conn.getAdmin(); HTableDescriptor tabDescriptor = new HTableDescriptor(tableName); HColumnDescriptor mob = new HColumnDescriptor("mobcf"); // Open mob function mob.setMobEnabled(true); // Set mob threshold mob.setMobThreshold(10L); tabDescriptor.addFamily(mob); admin.createTable(tabDescriptor); LOG.info("MOB Table is created successfully."); } catch (Exception e) { LOG.error("MOB Table is created failed ", e); } finally { if (admin != null) { try { // Close the Admin object. admin.close(); } catch (IOException e) { LOG.error("Close admin failed ", e); } } } LOG.info("Exiting testCreateMOBTable."); }
样例:用Put接口写入MOB数据
以下代码片段在com.bigdata.hbase.examples包的“HBaseExample”类的testMOBDataInsertion方法中
public void testMOBDataInsertion() { LOG.info("Entering testMOBDataInsertion."); Table table = null; try { // set row name to "row" Put p = new Put(Bytes.toBytes("row")); byte[] value = new byte[1000]; // set the column value of column family mobcf with the value of "cf1" p.addColumn(Bytes.toBytes("mobcf"), Bytes.toBytes("cf1"), value); // get the table object represent table tableName table = conn.getTable(tableName); // put data table.put(p); LOG.info("MOB data inserted successfully."); } catch (Exception e) { LOG.error("MOB data inserted failed ", e); } finally { if (table != null) { try { table.close(); } catch (Exception e1) { LOG.error("Close table failed ", e1); } } } LOG.info("Exiting testMOBDataInsertion."); }
注意事项
不允许多个线程在同一时间共用同一个HTable实例。HTable是一个非线程安全类,因此,同一个HTable实例,不应该被多个线程同时使用,否则可能会带来并发问题。