Hbase设计以及优化

一、表的设计

1.一、Column Familyhtml

因为Hbase是一个面向列族的存储器,调优和存储都是在列族这个层次上进行的,最好使列族成员都有相同的"访问模式(access pattern)"和大小特征
在一张表里不要定义太多的column family。目前Hbase并不能很好的处理超过2~3个column family的表。由于某个column family在flush的时候,它邻近的column family也会因关联效应被触发flush,最终致使系统产生更多的I/O。

java

1.二、Row Keyapache

Row Key 设计原则:
1)Rowkey长度原则,Rowkey是一个二进制码流,能够是任意字符串,最大长度64KB,实际应用中通常为10~100bytes,存为byte[]字节数组,通常设计成定长的建议是越短越好,不要超过16个字节。缘由一数据的持久化文件HFile中是按照KeyValue存储的,若是Rowkey过长好比100个字节,1000万列数据光Rowkey就要占用100*1000万=10亿个字节,将近1G数据,这会极大影响HFile的存储效率;缘由二MemStore将缓存部分数据到内存,若是Rowkey字段过长内存的有效利用率会下降,系统将没法缓存更多的数据,这会下降检索效率。所以Rowkey的字节长度越短越好。缘由三目前操做系统是都是64位系统,内存8字节对齐。控制在16个字节,8字节的整数倍利用操做系统的最佳特性。
2)是Rowkey散列原则,若是Rowkey是按时间戳的方式递增,不要将时间放在二进制码的前面,建议将Rowkey的高位做为散列字段,由程序循环生成,低位放时间字段,这样将提升数据均衡分布在每一个Regionserver实现负载均衡的概率。若是没有散列字段,首字段直接是时间信息将产生全部新数据都在一个RegionServer上堆积的热点现象,这样在作数据检索的时候负载将会集中在个别RegionServer,下降查询效率。
3)Rowkey惟一原则,必须在设计上保证其惟一性
row key是按照字典序存储,所以,设计row key时,要充分利用这个排序特色,将常常一块儿读取的数据存储到一块,将最近可能会被访问的数据放在一块。
举个例子:若是最近写入HBase表中的数据是最可能被访问的,能够考虑将时间戳做为row key的一部分,因为是字典序排序,因此可使用Long.MAX_VALUE – timestamp做为row key,这样能保证新写入的数据在读取时能够被快速命中。

数组

1.三、 In Memory缓存

建立表的时候,能够经过HColumnDescriptor.setInMemory(true)将表放到RegionServer的缓存中,保证在读取的时候被cache命中。网络

1.4 、Max Version多线程

建立表的时候,能够经过HColumnDescriptor.setMaxVersions(intmaxVersions)设置表中数据的最大版本,若是只须要保存最新版本的数据,那么能够设置setMaxVersions(1)。并发

1.五、 Time to Live(设置数据存储的生命周期)负载均衡

建立表的时候,能够经过HColumnDescriptor.setTimeToLive(inttimeToLive)设置表中数据的存储生命期,过时数据将自动被删除,例如若是只须要存储最近两天的数据,那么能够设置setTimeToLive(2 * 24 * 60 * 60)。ide

1.六、 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的发生

1.七、 Pre-Creating Regions

默认状况下,在建立HBase表的时候会自动建立一个region分区,当导入数据的时候,全部的HBase客户端都向这一个region写数据,直到这个region足够大了才进行切分。一种能够加快批量写入速度的方法是经过预先建立一些空的regions,这样当数据写入HBase时,会按照region分区状况,在集群内作数据的负载均衡。                              有关预分区,详情参见:TableCreation: Pre-Creating Regions,下面是一个例子:

  1. public static booleancreateTable(HBaseAdmin admin, HTableDescriptor table, byte[][] splits)  
  2. throws IOException {  
  3.   try {  
  4.     admin.createTable(table, splits);  
  5.     return true;  
  6.   } catch (TableExistsException e) {  
  7.     logger.info("table " +table.getNameAsString() + " already exists");  
  8.     // the table already exists...  
  9.     return false;  
  10.   }  
  11. }  
  12.    
  13. public static byte[][]getHexSplits(String startKey, String endKey, int numRegions) {  
  14.   byte[][] splits = new byte[numRegions-1][];  
  15.   BigInteger lowestKey = newBigInteger(startKey, 16);  
  16.   BigInteger highestKey = newBigInteger(endKey, 16);  
  17.   BigInteger range =highestKey.subtract(lowestKey);  
  18.   BigInteger regionIncrement =range.divide(BigInteger.valueOf(numRegions));  
  19.   lowestKey = lowestKey.add(regionIncrement);  
  20.   for(int i=0; i < numRegions-1;i++) {  
  21.     BigInteger key =lowestKey.add(regionIncrement.multiply(BigInteger.valueOf(i)));  
  22.     byte[] b = String.format("%016x",key).getBytes();  
  23.     splits[i] = b;  
  24.   }  
  25.   return splits;  
  26. }  
public static booleancreateTable(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 = newBigInteger(startKey, 16);
  BigInteger highestKey = newBigInteger(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;
}

二、写表操做

2.1 多HTable并发写

建立多个HTable客户端用于写操做,提升写数据的吞吐量,一个例子:

  1. static final Configurationconf = HBaseConfiguration.create();  
  2. static final Stringtable_log_name = “user_log”;  
  3. wTableLog = newHTable[tableN];  
  4. for (int i = 0; i <tableN; i++) {  
  5.     wTableLog[i] = new HTable(conf,table_log_name);  
  6.     wTableLog[i].setWriteBufferSize(5 * 1024 *1024); //5MB  
  7.     wTableLog[i].setAutoFlush(false);  
  8. }  
static final Configurationconf = HBaseConfiguration.create();
static final Stringtable_log_name = “user_log”;
wTableLog = newHTable[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是开启的。保证最后手动HTable.flushCommits()或HTable.close()

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。下面给个具体的例子:

  1. for (int i = 0; i <threadN; i++) {  
  2.     Thread th = new Thread() {  
  3.         public void run() {  
  4.             while (true) {  
  5.                 try {  
  6.                     sleep(1000); //1 second  
  7.                 } catch (InterruptedExceptione) {  
  8.                     e.printStackTrace();  
  9.                 }  
  10. synchronized (wTableLog[i]) {  
  11.                     try {  
  12.                         wTableLog[i].flushCommits();  
  13.                     } catch (IOException e) {  
  14.                         e.printStackTrace();  
  15.                     }  
  16.                 }  
  17.             }  
  18. }  
  19.     };  
  20.     th.setDaemon(true);  
  21.     th.start();  
  22. }  
for (int i = 0; i <threadN; i++) {
    Thread th = new Thread() {
        public void run() {
            while (true) {
                try {
                    sleep(1000); //1 second
                } catch (InterruptedExceptione) {
                    e.printStackTrace();
                }
synchronized (wTableLog[i]) {
                    try {
                        wTableLog[i].flushCommits();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
}
    };
    th.setDaemon(true);
    th.start();
}

三、读表操做

3.1 多HTable并发读

建立多个HTable客户端用于读操做,提升读数据的吞吐量,一个例子:

  1. static final Configurationconf = HBaseConfiguration.create();  
  2. static final Stringtable_log_name = “user_log”;  
  3. rTableLog = newHTable[tableN];  
  4. for (int i = 0; i <tableN; i++) {  
  5.     rTableLog[i] = new HTable(conf, table_log_name);  
  6.     rTableLog[i].setScannerCaching(50);  
  7. }  
static final Configurationconf = HBaseConfiguration.create();
static final Stringtable_log_name = “user_log”;
rTableLog = newHTable[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

hbase.client.scanner.caching配置项能够设置HBase scanner一次从服务端抓取的数据条数,默认状况下一次一条。经过将其设置成一个合理的值,能够减小scan过程当中next()的时间开销,代价是 scanner须要经过客户端的内存来维持这些被cache的行记录。

有三个地方能够进行配置:1)在HBase的conf配置文件中进行配置;2)经过调用HTable.setScannerCaching(int scannerCaching)进行配置;3)经过调用Scan.setCaching(int caching)进行配置。三者的优先级愈来愈高。

3.2.2 Scan AttributeSelection

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

3.4 多线程并发读

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

  1. public class DataReaderServer{  
  2.      //获取店铺一天内各分钟PV值的入口函数  
  3.      public static ConcurrentHashMap<String,String> getUnitMinutePV(long uid, long startStamp, long endStamp){  
  4.          long min = startStamp;  
  5.          int count = (int)((endStamp -startStamp) / (60*1000));  
  6.          List<String> lst = newArrayList<String>();  
  7.          for (int i = 0; i <= count; i++) {  
  8.             min = startStamp + i * 60 * 1000;  
  9.             lst.add(uid + "_" + min);  
  10.          }  
  11.          return parallelBatchMinutePV(lst);  
  12.      }  
  13.       //多线程并发查询,获取分钟PV值  
  14. private staticConcurrentHashMap<String, String>parallelBatchMinutePV(List<String> lstKeys){  
  15.         ConcurrentHashMap<String, String>hashRet = new ConcurrentHashMap<String, String>();  
  16.         int parallel = 3;  
  17.         List<List<String>>lstBatchKeys  = null;  
  18.         if (lstKeys.size() < parallel ){  
  19.             lstBatchKeys  = new ArrayList<List<String>>(1);  
  20.             lstBatchKeys.add(lstKeys);  
  21.         }  
  22.         else{  
  23.             lstBatchKeys  = newArrayList<List<String>>(parallel);  
  24.             for(int i = 0; i < parallel;i++  ){  
  25.                 List<String> lst = newArrayList<String>();  
  26.                 lstBatchKeys.add(lst);  
  27.             }  
  28.             for(int i = 0 ; i <lstKeys.size() ; i ++ ){  
  29.                lstBatchKeys.get(i%parallel).add(lstKeys.get(i));  
  30.             }  
  31.         }  
  32.         List<Future<ConcurrentHashMap<String, String> >> futures = newArrayList<Future< ConcurrentHashMap<String, String> >>(5);  
  33.         ThreadFactoryBuilder builder = newThreadFactoryBuilder();  
  34.        builder.setNameFormat("ParallelBatchQuery");  
  35.         ThreadFactory factory =builder.build();  
  36.         ThreadPoolExecutor executor =(ThreadPoolExecutor) Executors.newFixedThreadPool(lstBatchKeys.size(),factory);  
  37.         for(List<String> keys :lstBatchKeys){  
  38.             Callable<ConcurrentHashMap<String, String> > callable = newBatchMinutePVCallable(keys);  
  39.             FutureTask<ConcurrentHashMap<String, String> > future = (FutureTask<ConcurrentHashMap<String, String> >) executor.submit(callable);  
  40.             futures.add(future);  
  41.         }  
  42.         executor.shutdown();  
  43.         // Wait for all the tasks to finish  
  44.         try {  
  45.           boolean stillRunning = !executor.awaitTermination(  
  46.               5000000, TimeUnit.MILLISECONDS);  
  47.           if (stillRunning) {  
  48.             try {  
  49.                 executor.shutdownNow();  
  50.             } catch (Exception e) {  
  51.                 // TODO Auto-generated catchblock  
  52.                 e.printStackTrace();  
  53.             }  
  54.           }  
  55.         } catch (InterruptedException e) {  
  56.           try {  
  57.              Thread.currentThread().interrupt();  
  58.           } catch (Exception e1) {  
  59.             // TODO Auto-generated catch block  
  60.             e1.printStackTrace();  
  61.           }  
  62.         }  
  63.         // Look for any exception  
  64.         for (Future f : futures) {  
  65.           try {  
  66.               if(f.get() != null)  
  67.               {  
  68.                  hashRet.putAll((ConcurrentHashMap<String, String>)f.get());  
  69.               }  
  70.           } catch (InterruptedException e) {  
  71.             try {  
  72.                 Thread.currentThread().interrupt();  
  73.             } catch (Exception e1) {  
  74.                 // TODO Auto-generated catchblock  
  75.                 e1.printStackTrace();  
  76.             }  
  77.           } catch (ExecutionException e) {  
  78.             e.printStackTrace();  
  79.           }  
  80.         }  
  81.         return hashRet;  
  82.     }  
  83.      //一个线程批量查询,获取分钟PV值  
  84.     protected staticConcurrentHashMap<String, String> getBatchMinutePV(List<String>lstKeys){  
  85.         ConcurrentHashMap<String, String>hashRet = null;  
  86.         List<Get> lstGet = newArrayList<Get>();  
  87.         String[] splitValue = null;  
  88.         for (String s : lstKeys) {  
  89.             splitValue =s.split("_");  
  90.             long uid =Long.parseLong(splitValue[0]);  
  91.             long min =Long.parseLong(splitValue[1]);  
  92.             byte[] key = new byte[16];  
  93.             Bytes.putLong(key, 0, uid);  
  94.             Bytes.putLong(key, 8, min);  
  95.             Get g = new Get(key);  
  96.             g.addFamily(fp);  
  97.             lstGet.add(g);  
  98.         }  
  99.         Result[] res = null;  
  100.         try {  
  101.             res =tableMinutePV[rand.nextInt(tableN)].get(lstGet);  
  102.         } catch (IOException e1) {  
  103.             logger.error("tableMinutePV exception,e=" + e1.getStackTrace());  
  104.         }  
  105.         if (res != null && res.length> 0) {  
  106.             hashRet = newConcurrentHashMap<String, String>(res.length);  
  107.             for (Result re : res) {  
  108.                 if (re != null &&!re.isEmpty()) {  
  109.                     try {  
  110.                         byte[] key =re.getRow();  
  111.                         byte[] value =re.getValue(fp, cp);  
  112.                         if (key != null&& value != null) {  
  113.                            hashRet.put(String.valueOf(Bytes.toLong(key,  
  114.                                    Bytes.SIZEOF_LONG)), String.valueOf(Bytes  
  115.                                    .toLong(value)));  
  116.                         }  
  117.                     } catch (Exception e2) {  
  118.                        logger.error(e2.getStackTrace());  
  119.                     }  
  120.                 }  
  121.             }  
  122.         }  
  123.         return hashRet;  
  124.     }  
  125. }  
  126. //调用接口类,实现Callable接口  
  127. class BatchMinutePVCallableimplements Callable<ConcurrentHashMap<String, String>>{  
  128.      private List<String> keys;  
  129.      publicBatchMinutePVCallable(List<String> lstKeys ) {  
  130.          this.keys = lstKeys;  
  131.      }  
  132.      public ConcurrentHashMap<String,String> call() throws Exception {  
  133.          returnDataReadServer.getBatchMinutePV(keys);  
  134.      }  
  135. }  
public class DataReaderServer{
     //获取店铺一天内各分钟PV值的入口函数
     public static ConcurrentHashMap<String,String> getUnitMinutePV(long uid, long startStamp, long endStamp){
         long min = startStamp;
         int count = (int)((endStamp -startStamp) / (60*1000));
         List<String> lst = newArrayList<String>();
         for (int i = 0; i <= count; i++) {
            min = startStamp + i * 60 * 1000;
            lst.add(uid + "_" + min);
         }
         return parallelBatchMinutePV(lst);
     }
      //多线程并发查询,获取分钟PV值
private staticConcurrentHashMap<String, String>parallelBatchMinutePV(List<String> lstKeys){
        ConcurrentHashMap<String, String>hashRet = new ConcurrentHashMap<String, String>();
        int parallel = 3;
        List<List<String>>lstBatchKeys  = null;
        if (lstKeys.size() < parallel ){
            lstBatchKeys  = new ArrayList<List<String>>(1);
            lstBatchKeys.add(lstKeys);
        }
        else{
            lstBatchKeys  = newArrayList<List<String>>(parallel);
            for(int i = 0; i < parallel;i++  ){
                List<String> lst = newArrayList<String>();
                lstBatchKeys.add(lst);
            }
            for(int i = 0 ; i <lstKeys.size() ; i ++ ){
               lstBatchKeys.get(i%parallel).add(lstKeys.get(i));
            }
        }
        List<Future<ConcurrentHashMap<String, String> >> futures = newArrayList<Future< ConcurrentHashMap<String, String> >>(5);
        ThreadFactoryBuilder builder = newThreadFactoryBuilder();
       builder.setNameFormat("ParallelBatchQuery");
        ThreadFactory factory =builder.build();
        ThreadPoolExecutor executor =(ThreadPoolExecutor) Executors.newFixedThreadPool(lstBatchKeys.size(),factory);
        for(List<String> keys :lstBatchKeys){
            Callable<ConcurrentHashMap<String, String> > callable = newBatchMinutePVCallable(keys);
            FutureTask<ConcurrentHashMap<String, String> > future = (FutureTask<ConcurrentHashMap<String, String> >) 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 catchblock
                e.printStackTrace();
            }
          }
        } catch (InterruptedException e) {
          try {
             Thread.currentThread().interrupt();
          } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
          }
        }
        // Look for any exception
        for (Future f : futures) {
          try {
              if(f.get() != null)
              {
                 hashRet.putAll((ConcurrentHashMap<String, String>)f.get());
              }
          } catch (InterruptedException e) {
            try {
                Thread.currentThread().interrupt();
            } catch (Exception e1) {
                // TODO Auto-generated catchblock
                e1.printStackTrace();
            }
          } catch (ExecutionException e) {
            e.printStackTrace();
          }
        }
        return hashRet;
    }
     //一个线程批量查询,获取分钟PV值
    protected staticConcurrentHashMap<String, String> getBatchMinutePV(List<String>lstKeys){
        ConcurrentHashMap<String, String>hashRet = null;
        List<Get> lstGet = newArrayList<Get>();
        String[] splitValue = null;
        for (String s : lstKeys) {
            splitValue =s.split("_");
            long uid =Long.parseLong(splitValue[0]);
            long min =Long.parseLong(splitValue[1]);
            byte[] key = new byte[16];
            Bytes.putLong(key, 0, uid);
            Bytes.putLong(key, 8, min);
            Get g = new Get(key);
            g.addFamily(fp);
            lstGet.add(g);
        }
        Result[] res = null;
        try {
            res =tableMinutePV[rand.nextInt(tableN)].get(lstGet);
        } catch (IOException e1) {
            logger.error("tableMinutePV exception,e=" + e1.getStackTrace());
        }
        if (res != null && res.length> 0) {
            hashRet = newConcurrentHashMap<String, String>(res.length);
            for (Result re : res) {
                if (re != null &&!re.isEmpty()) {
                    try {
                        byte[] key =re.getRow();
                        byte[] value =re.getValue(fp, cp);
                        if (key != null&& value != null) {
                           hashRet.put(String.valueOf(Bytes.toLong(key,
                                   Bytes.SIZEOF_LONG)), String.valueOf(Bytes
                                   .toLong(value)));
                        }
                    } catch (Exception e2) {
                       logger.error(e2.getStackTrace());
                    }
                }
            }
        }
        return hashRet;
    }
}
//调用接口类,实现Callable接口
class BatchMinutePVCallableimplements Callable<ConcurrentHashMap<String, String>>{
     private List<String> keys;
     publicBatchMinutePVCallable(List<String> lstKeys ) {
         this.keys = lstKeys;
     }
     public ConcurrentHashMap<String,String> call() throws Exception {
         returnDataReadServer.getBatchMinutePV(keys);
     }
}

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,以加大缓存的命中率

相关文章
相关标签/搜索