HBase性能优化方法总结(4):读表操作

HBase性能优化方法总结(4):读表操作

3 已有 344 次阅读  2012-09-05 13:26   标签:  优化  表 
本文主要是从HBase应用程序设计与开发的角度,总结几种常用的性能优化方法。有关HBase系统配置级别的优化,可参考: 淘宝Ken Wu同学的博客。

下面是本文总结的第三部分内容:读表操作相关的优化方法。

3. 读表操作

3.1 多HTable并发读

创建多个HTable客户端用于读操作,提高读数据的吞吐量,一个例子:

view source
print ?
1 static final Configuration conf = HBaseConfiguration.create();
2 static final String table_log_name = “user_log”;
3 rTableLog = new HTable[tableN];
4 for (int i = 0; i < tableN; i++) {
5     rTableLog[i] = new HTable(conf, table_log_name);
6     rTableLog[i].setScannerCaching(50);
7 }

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<Get>)方法可以根据一个指定的row key列表,批量获取多行记录,这样做的好处是批量执行,只需要一次网络I/O开销,这对于对数据实时性要求高而且网络传输RTT高的情景下可能带来明显的性能提升。

3.4 多线程并发读

在客户端开启多个HTable读线程,每个读线程负责通过HTable对象进行get操作。下面是一个多线程并发读取HBase,获取店铺一天内各分钟PV值的例子:

view source
print ?
001 public class DataReaderServer {
002      //获取店铺一天内各分钟PV值的入口函数
003      public static ConcurrentHashMap<String, String> getUnitMinutePV(long uid, long startStamp, long endStamp){
004          long min = startStamp;
005          int count = (int)((endStamp - startStamp) / (60*1000));
006          List<String> lst = new ArrayList<String>();
007          for (int i = 0; i <= count; i++) {
008             min = startStamp + i * 60 * 1000;
009             lst.add(uid + "_" + min);
010          }
011          return parallelBatchMinutePV(lst);
012      }
013       //多线程并发查询,获取分钟PV值
014 private static ConcurrentHashMap<String, String> parallelBatchMinutePV(List<String> lstKeys){
015         ConcurrentHashMap<String, String> hashRet = new ConcurrentHashMap<String, String>();
016         int parallel = 3;
017         List<List<String>> lstBatchKeys  = null;
018         if (lstKeys.size() < parallel ){
019             lstBatchKeys  = new ArrayList<List<String>>(1);
020             lstBatchKeys.add(lstKeys);
021         }
022         else{
023             lstBatchKeys  = new ArrayList<List<String>>(parallel);
024             for(int i = 0; i < parallel; i++  ){
025                 List<String> lst = new ArrayList<String>();
026                 lstBatchKeys.add(lst);
027             }
028   
029             for(int i = 0 ; i < lstKeys.size() ; i ++ ){
030                 lstBatchKeys.get(i%parallel).add(lstKeys.get(i));
031             }
032         }
033           
034         List<Future< ConcurrentHashMap<String, String> >> futures = new ArrayList<Future< ConcurrentHashMap<String, String> >>(5);
035           
036         ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
037         builder.setNameFormat("ParallelBatchQuery");
038         ThreadFactory factory = builder.build();
039         ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(lstBatchKeys.size(), factory);
040           
041         for(List<String> keys : lstBatchKeys){
042             Callable< ConcurrentHashMap<String, String> > callable = new BatchMinutePVCallable(keys);
043             FutureTask< ConcurrentHashMap<String, String> > future = (FutureTask< ConcurrentHashMap<String, String> >) executor.submit(callable);
044             futures.add(future);
045         }
046         executor.shutdown();
047           
048         // Wait for all the tasks to finish
049         try {
050           boolean stillRunning = !executor.awaitTermination(
051               5000000, TimeUnit.MILLISECONDS);
052           if (stillRunning) {
053             try {
054                 executor.shutdownNow();
055             } catch (Exception e) {
056                 // TODO Auto-generated catch block
057                 e.printStackTrace();
058             }
059           }
060         } catch (InterruptedException e) {
061           try {
062               Thread.currentThread().interrupt();
063           } catch (Exception e1) {
064             // TODO Auto-generated catch block
065             e1.printStackTrace();
066           }
067         }
068           
069         // Look for any exception
070         for (Future f : futures) {
071           try {
072               if(f.get() != null)
073               {
074                   hashRet.putAll((ConcurrentHashMap<String, String>)f.get());
075               }
076           } catch (InterruptedException e) {
077             try {
078                  Thread.currentThread().interrupt();
079             } catch (Exception e1) {
080                 // TODO Auto-generated catch block
081                 e1.printStackTrace();
082             }
083           } catch (ExecutionException e) {
084             e.printStackTrace();
085           }
086         }
087           
088         return hashRet;
089     }
090      //一个线程批量查询,获取分钟PV值
091     protected static ConcurrentHashMap<String, String> getBatchMinutePV(List<String> lstKeys){
092         ConcurrentHashMap<String, String> hashRet = null;
093         List<Get> lstGet = new ArrayList<Get>();
094         String[] splitValue = null;
095         for (String s : lstKeys) {
096             splitValue = s.split("_");
097             long uid = Long.parseLong(splitValue[0]);
098             long min = Long.parseLong(splitValue[1]);
099             byte[] key = new byte[16];
100             Bytes.putLong(key, 0, uid);
101             Bytes.putLong(key, 8, min);
102             Get g = new Get(key);
103             g.addFamily(fp);
104             lstGet.add(g);
105         }
106         Result[] res = null;
107         try {
108             res = tableMinutePV[rand.nextInt(tableN)].get(lstGet);
109         } catch (IOException e1) {
110             logger.error("tableMinutePV exception, e=" + e1.getStackTrace());
111         }
112   
113         if (res != null && res.length > 0) {
114             hashRet = new ConcurrentHashMap<String, String>(res.length);
115             for (Result re : res) {
116                 if (re != null && !re.isEmpty()) {
117                     try {
118                         byte[] key = re.getRow();
119                         byte[] value = re.getValue(fp, cp);
120                         if (key != null && value != null) {
121                             hashRet.put(String.valueOf(Bytes.toLong(key,
122                                     Bytes.SIZEOF_LONG)), String.valueOf(Bytes
123                                     .toLong(value)));
124                         }
125                     } catch (Exception e2) {
126                         logger.error(e2.getStackTrace());
127                     }
128                 }
129             }
130         }
131   
132         return hashRet;
133     }
134 }
135 //调用接口类,实现Callable接口
136 class BatchMinutePVCallable implements Callable<ConcurrentHashMap<String, String>>{
137      private List<String> keys;
138   
139      public BatchMinutePVCallable(List<String> lstKeys ) {
140          this.keys = lstKeys;
141      }
142   
143      public ConcurrentHashMap<String, String> call() throws Exception {
144          return DataReadServer.getBatchMinutePV(keys);
145      }
146 }

3.5 缓存查询结果

对于频繁查询HBase的应用场景,可以考虑在应用程序中做缓存,当有新的查询请求时,首先在缓存中查找,如果存在则直接返回,不再查询HBase;否则对HBase发起读请求查询,然后在应用程序中将查询结果缓存起来。至于缓存的替换策略,可以考虑LRU等常用的策略。

3.6 Blockcache

HBase上Regionserver的内存分为两个部分,一部分作为Memstore,主要用来写;另外一部分作为BlockCache,主要用于读。

写请求会先写入Memstore,Regionserver会给每个region提供一个Memstore,当Memstore满64MB以后,会启动 flush刷新到磁盘。当Memstore的总大小超过限制时(heapsize * hbase.regionserver.global.memstore.upperLimit * 0.9),会强行启动flush进程,从最大的Memstore开始flush直到低于限制。

读请求先到Memstore中查数据,查不到就到BlockCache中查,再查不到就会到磁盘上读,并把读的结果放入BlockCache。由于BlockCache采用的是LRU策略,因此BlockCache达到上限(heapsize * hfile.block.cache.size * 0.85)后,会启动淘汰机制,淘汰掉最老的一批数据。

一个Regionserver上有一个BlockCache和N个Memstore,它们的大小之和不能大于等于heapsize * 0.8,否则HBase不能启动。默认BlockCache为0.2,而Memstore为0.4。对于注重读响应时间的系统,可以将 BlockCache设大些,比如设置BlockCache=0.4,Memstore=0.39,以加大缓存的命中率。

有关BlockCache机制,请参考这里:HBase的Block cache,HBase的blockcache机制,hbase中的缓存的计算与使用。

你可能感兴趣的:(HBase性能优化方法总结(4):读表操作)