HBase設計與開發效能最佳化

來源:互聯網
上載者:User
1. 表的設計 1.1 Pre-Creating Regions

預設情況下,在建立HBase表的時候會自動建立一個region分區,當匯入資料的時候,所有的HBase用戶端都向這一個region寫資料,直到這個region足夠大了才進行切分。一種可以加快批量寫入速度的方法是通過預先建立一些空的regions,這樣當資料寫入HBase時,會按照region分區情況,在叢集內做資料的負載平衡。

有關預分區,詳情參見:Table Creation: Pre-Creating Regions,下面是一個例子:

public static boolean createTable(HBaseAdmin admin, HTableDescriptor table, byte[][] splits)  throws IOException {  try {    admin.createTable(table, splits);    return true;  } catch (TableExistsException e) {    logger.info("table " + table.getNameAsString() + " already exists");    // the table already exists...    return false;  }} public static byte[][] getHexSplits(String startKey, String endKey, int numRegions) {  byte[][] splits = new byte[numRegions-1][];  BigInteger lowestKey = new BigInteger(startKey, 16);  BigInteger highestKey = new BigInteger(endKey, 16);  BigInteger range = highestKey.subtract(lowestKey);  BigInteger regionIncrement = range.divide(BigInteger.valueOf(numRegions));  lowestKey = lowestKey.add(regionIncrement);  for(int i=0; i < numRegions-1;i++) {    BigInteger key = lowestKey.add(regionIncrement.multiply(BigInteger.valueOf(i)));    byte[] b = String.format("%016x", key).getBytes();    splits[i] = b;  }  return splits;}

  1.2 Row Key

HBase中row key用來檢索表中的記錄,支援以下三種方式: 通過單個row key訪問:即按照某個row key索引值進行get操作; 通過row key的range進行scan:即通過設定startRowKey和endRowKey,在這個範圍內進行掃描; 全表掃描:即直接掃描整張表中所有行記錄。

在HBase中,row key可以是任一字元串,最大長度64KB,實際應用中一般為10~100bytes,存為byte[]位元組數組,一般設計成定長的。

row key是按照字典序儲存,因此,設計row key時,要充分利用這個排序特點,將經常一起讀取的資料存放區到一塊,將最近可能會被訪問的資料放在一塊。

舉個例子:如果最近寫入HBase表中的資料是最可能被訪問的,可以考慮將時間戳記作為row key的一部分,由於是字典序排序,所以可以使用Long.MAX_VALUE – timestamp作為row key,這樣能保證新寫入的資料在讀取時可以被快速命中。 1.3 Column Family

不要在一張表裡定義太多的column family。目前Hbase並不能很好的處理超過2~3個column family的表。因為某個column family在flush的時候,它鄰近的column family也會因關聯效應被觸發flush,最終導致系統產生更多的I/O。感興趣的同學可以對自己的HBase叢集進行實際測試,從得到的測試結果資料驗證一下。 1.4 In Memory

建立表的時候,可以通過HColumnDescriptor.setInMemory(true)將表放到RegionServer的緩衝中,保證在讀取的時候被cache命中。 1.5 Max Version

建立表的時候,可以通過HColumnDescriptor.setMaxVersions(int maxVersions)設定表中資料的最大版本,如果只需要儲存最新版本的資料,那麼可以設定setMaxVersions(1)。 1.6 Time To Live

建立表的時候,可以通過HColumnDescriptor.setTimeToLive(int timeToLive)設定表中資料的儲存生命期,到期資料將自動被刪除,例如如果只需要儲存最近兩天的資料,那麼可以設定setTimeToLive(2 * 24 * 60 * 60)。 1.7 Compact & Split

在HBase中,資料在更新時首先寫入WAL 日誌(HLog)和記憶體(MemStore)中,MemStore中的資料是排序的,當MemStore累計到一定閾值時,就會建立一個新的MemStore,並且將老的MemStore添加到flush隊列,由單獨的線程flush到磁碟上,成為一個StoreFile。於此同時, 系統會在zookeeper中記錄一個redo point,表示這個時刻之前的變更已經持久化了(minor compact)。

StoreFile是唯讀,一旦建立後就不可以再修改。因此Hbase的更新其實是不斷追加的操作。當一個Store中的StoreFile達到一定的閾值後,就會進行一次合并(major compact),將對同一個key的修改合并到一起,形成一個大的StoreFile,當StoreFile的大小達到一定閾值後,又會對 StoreFile進行分割(split),等分為兩個StoreFile。

由於對錶的更新是不斷追加的,處理讀請求時,需要訪問Store中全部的StoreFile和MemStore,將它們按照row key進行合并,由於StoreFile和MemStore都是經過排序的,並且StoreFile帶有記憶體中索引,通常合并過程還是比較快的。

實際應用中,可以考慮必要時手動進行major compact,將同一個row key的修改進行合并形成一個大的StoreFile。同時,可以將StoreFile設定大些,減少split的發生。 2. 寫表操作 2.1 多HTable並發寫

建立多個HTable用戶端用於寫操作,提高寫資料的輸送量,一個例子:

static final Configuration conf = HBaseConfiguration.create();static final String table_log_name = “user_log”;wTableLog = new HTable[tableN];for (int i = 0; i < tableN; i++) {    wTableLog[i] = new HTable(conf, table_log_name);    wTableLog[i].setWriteBufferSize(5 * 1024 * 1024); //5MB    wTableLog[i].setAutoFlush(false);}

  2.2 HTable參數設定 2.2.1 Auto Flush

通過調用HTable.setAutoFlush(false)方法可以將HTable寫用戶端的自動flush關閉,這樣可以批量寫入資料到HBase,而不是有一條put就執行一次更新,只有當put填滿用戶端寫緩衝時,才實際向HBase服務端發起寫請求。預設情況下auto flush是開啟的。 2.2.2 Write Buffer

通過調用HTable.setWriteBufferSize(writeBufferSize)方法可以設定HTable用戶端的寫buffer大小,如果新設定的buffer小於當前寫buffer中的資料時,buffer將會被flush到服務端。其中,writeBufferSize的單位是byte位元組數,可以根據實際寫入資料量的多少來設定該值。 2.2.3 WAL Flag

在HBae中,用戶端向叢集中的RegionServer提交資料時(Put/Delete操作),首先會先寫WAL(Write Ahead Log)日誌(即HLog,一個RegionServer上的所有Region共用一個HLog),只有當WAL日誌寫成功後,再接著寫MemStore,然後用戶端被通知提交資料成功;如果寫WAL日誌失敗,用戶端則被通知提交失敗。這樣做的好處是可以做到RegionServer宕機後的資料恢複。

因此,對於相對不太重要的資料,可以在Put/Delete操作時,通過調用Put.setWriteToWAL(false)或Delete.setWriteToWAL(false)函數,放棄寫WAL日誌,從而提高資料寫入的效能。

值得注意的是:謹慎選擇關閉WAL日誌,因為這樣的話,一旦RegionServer宕機,Put/Delete的資料將會無法根據WAL日誌進行恢複。 2.3 批量寫

通過調用HTable.put(Put)方法可以將一個指定的row key記錄寫入HBase,同樣HBase提供了另一個方法:通過調用HTable.put(List<Put>)方法可以將指定的row key列表,批量寫入多行記錄,這樣做的好處是批量執行,只需要一次網路I/O開銷,這對於對資料即時性要求高,網路傳輸RTT高的情景下可能帶來明顯的效能提升。 2.4 多線程並發寫

在用戶端開啟多個HTable寫線程,每個寫線程負責一個HTable對象的flush操作,這樣結合定時flush和寫buffer(writeBufferSize),可以既保證在資料量小的時候,資料可以在較短時間內被flush(如1秒內),同時又保證在資料量大的時候,寫buffer一滿就及時進行flush。下面給個具體的例子:

for (int i = 0; i < threadN; i++) {    Thread th = new Thread() {        public void run() {            while (true) {                try {                    sleep(1000); //1 second                } catch (InterruptedException e) {                    e.printStackTrace();                }                                synchronized (wTableLog[i]) {                    try {                        wTableLog[i].flushCommits();                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }                }    };    th.setDaemon(true);    th.start();}

  3. 讀表操作 3.1 多HTable並發讀

建立多個HTable用戶端用於讀操作,提高讀資料的輸送量,一個例子:

static final Configuration conf = HBaseConfiguration.create();static final String table_log_name = “user_log”;rTableLog = new HTable[tableN];for (int i = 0; i < tableN; i++) {    rTableLog[i] = new HTable(conf, table_log_name);    rTableLog[i].setScannerCaching(50);}

  3.2 HTable參數設定 3.2.1 Scanner Caching

通過調用HTable.setScannerCaching(int scannerCaching)可以設定HBase scanner一次從服務端抓取的資料條數,預設情況下一次一條。通過將此值設定成一個合理的值,可以減少scan過程中next()的時間開銷,代價是scanner需要通過用戶端的記憶體來維持這些被cache的行記錄。 3.2.2 Scan Attribute Selection

scan時指定需要的Column Family,可以減少網路傳輸資料量,否則預設scan操作會返回整行所有Column Family的資料。 3.2.3 Close ResultScanner

通過scan取完資料後,記得要關閉ResultScanner,否則RegionServer可能會出現問題(對應的Server資源無法釋放)。 3.3 批量讀

通過調用HTable.get(Get)方法可以根據一個指定的row key擷取一行記錄,同樣HBase提供了另一個方法:通過調用HTable.get(List)方法可以根據一個指定的row key列表,批量擷取多行記錄,這樣做的好處是批量執行,只需要一次網路I/O開銷,這對於對資料即時性要求高而且網路傳輸RTT高的情景下可能帶來明顯的效能提升。 3.4 多線程並發讀

在用戶端開啟多個HTable讀線程,每個讀線程負責通過HTable對象進行get操作。下面是一個多線程並發讀取HBase,擷取店鋪一天內各分鐘PV值的例子:

public class DataReaderServer {     //擷取店鋪一天內各分鐘PV值的入口函數     public static ConcurrentHashMap getUnitMinutePV(long uid, long startStamp, long endStamp){         long min = startStamp;         int count = (int)((endStamp - startStamp) / (60*1000));         List lst = new ArrayList();         for (int i = 0; i <= count; i++) {            min = startStamp + i * 60 * 1000;            lst.add(uid + "_" + min);         }         return parallelBatchMinutePV(lst);     }      //多線程並發查詢,擷取分鐘PV值private static ConcurrentHashMap parallelBatchMinutePV(List lstKeys){        ConcurrentHashMap hashRet = new ConcurrentHashMap();        int parallel = 3;        List<List<String>> lstBatchKeys  = null;        if (lstKeys.size() < parallel ){            lstBatchKeys  = new ArrayList<List<String>>(1);            lstBatchKeys.add(lstKeys);        }        else{            lstBatchKeys  = new ArrayList<List<String>>(parallel);            for(int i = 0; i < parallel; i++  ){                List lst = new ArrayList();                lstBatchKeys.add(lst);            }             for(int i = 0 ; i < lstKeys.size() ; i ++ ){                lstBatchKeys.get(i%parallel).add(lstKeys.get(i));            }        }         List >> futures = new ArrayList >>(5);         ThreadFactoryBuilder builder = new ThreadFactoryBuilder();        builder.setNameFormat("ParallelBatchQuery");        ThreadFactory factory = builder.build();        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(lstBatchKeys.size(), factory);         for(List keys : lstBatchKeys){            Callable< ConcurrentHashMap > callable = new BatchMinutePVCallable(keys);            FutureTask< ConcurrentHashMap > future = (FutureTask< ConcurrentHashMap >) executor.submit(callable);            futures.add(future);        }        executor.shutdown();         // Wait for all the tasks to finish        try {          boolean stillRunning = !executor.awaitTermination(              5000000, TimeUnit.MILLISECONDS);          if (stillRunning) {            try {                executor.shutdownNow();            } catch (Exception e) {                // TODO Auto-generated catch block                e.printStackTrace();            }          }        } catch (InterruptedException e) {          try {              Thread.currentThread().interrupt();          } catch

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.