HBase學習之三: hbase filter(過濾器)和coprocessor(協處理器)統計行數的簡單應用
阿新 • • 發佈:2019-01-30
2.通過coprocessor統計行數
關於協處理器的介紹和用法網上很多資料,可以自行查詢腦補,值得注意的是協處理器在hbase伺服器端執行,開發者可自定義處理器放置於伺服器端然後再客戶端呼叫,下面是一個簡單的通過協處理器統計表行數的例子:
要使得上述程式碼生效,還必須需要讓要統計的表具有聚合功能。如下在hbase shell執行下面的命令:<span style="font-family:Arial Black;"><span style="font-family:Times New Roman;"> AggregationClient aggregation = new AggregationClient(conf); Long count = aggregation.rowCount(table, new LongColumnInterpreter(), s);//table為HTable例項,s為Scan例項 int totalCount = count.intValue();</span></span>
* disable 'emp'
* alter 'emp',METHOD=>'table_att','coprocessor'=>'|org.apache.hadoop.hbase.coprocessor.AggregateImplementation||'
* enable 'emp'
要刪除協處理器,如下:
* disable 'emp'
* alter 'emp',METHOD=>'table_att_unset',NAME=>'coprocessor$1'
* enable 'emp'
現實情況是不可能統計一個表的行數前去命令列執行下命令,於是可在統計行數前加上如下程式碼:
<span style="font-family:Arial Black;"><span style="font-family:Times New Roman;"> /** * 使表具有聚合功能 * * @param tableName * 表名 */ @SuppressWarnings("resource") private void enableAggregation(String tableName) { String coprocessorName = "org.apache.hadoop.hbase.coprocessor.AggregateImplementation"; try { HBaseAdmin admin = new HBaseAdmin(conf); HTableDescriptor htd = admin.getTableDescriptor(Bytes .toBytes(tableName)); List<String> coprocessors = htd.getCoprocessors(); if (coprocessors != null && coprocessors.size() > 0) { return; } else { admin.disableTable(tableName); htd.addCoprocessor(coprocessorName); admin.modifyTable(tableName, htd); admin.enableTable(tableName); } } catch (TableNotFoundException e) { // TODO Auto-generated catch block log.error(e); } catch (MasterNotRunningException e) { // TODO Auto-generated catch block log.error(e); } catch (ZooKeeperConnectionException e) { // TODO Auto-generated catch block log.error(e); } catch (IOException e) { // TODO Auto-generated catch block log.error(e); } }</span></span>