hbase api常用方法使用及预分区解决热点问题

来源:互联网 发布:手机听歌软件 编辑:程序博客网 时间:2024/05/22 04:37

API 操作:

[java] view plaincopy
  1. import java.io.IOException;  
  2. import java.util.ArrayList;  
  3. import java.util.List;  
  4.   
  5. import org.apache.hadoop.conf.Configuration;  
  6. import org.apache.hadoop.hbase.HBaseConfiguration;  
  7. import org.apache.hadoop.hbase.HColumnDescriptor;  
  8. import org.apache.hadoop.hbase.HTableDescriptor;  
  9. import org.apache.hadoop.hbase.KeyValue;  
  10. import org.apache.hadoop.hbase.MasterNotRunningException;  
  11. import org.apache.hadoop.hbase.TableName;  
  12. import org.apache.hadoop.hbase.ZooKeeperConnectionException;  
  13. import org.apache.hadoop.hbase.client.Get;  
  14. import org.apache.hadoop.hbase.client.HBaseAdmin;  
  15. import org.apache.hadoop.hbase.client.HTable;  
  16. import org.apache.hadoop.hbase.client.HTablePool;  
  17. import org.apache.hadoop.hbase.client.Put;  
  18. import org.apache.hadoop.hbase.client.Result;  
  19. import org.apache.hadoop.hbase.client.ResultScanner;  
  20. import org.apache.hadoop.hbase.client.Scan;  
  21. import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;  
  22. import org.apache.hadoop.hbase.filter.Filter;  
  23. import org.apache.hadoop.hbase.filter.FilterList;  
  24. import org.apache.hadoop.hbase.filter.PrefixFilter;  
  25. import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;  
  26. import org.apache.hadoop.hbase.util.Bytes;  
  27. import org.slf4j.Logger;  
  28. import org.slf4j.LoggerFactory;  
  29.   
  30. import com.kktest.hbase.HashChoreWoker;  
  31. import com.kktest.hbase.HashRowKeyGenerator;  
  32. import com.kktest.hbase.RowKeyGenerator;  
  33. import com.kktest.hbase.BitUtils;  
  34.   
  35. /** 
  36.  * hbase 客户端 
  37.  *  
  38.  * @author kuang hj 
  39.  *  
  40.  */  
  41. @SuppressWarnings("all")  
  42. public class HBaseClient {  
  43.   
  44.     private static Logger logger = LoggerFactory.getLogger(HBaseClient.class);  
  45.     private static Configuration config;  
  46.     static {  
  47.         config = HBaseConfiguration.create();  
  48.         config.set("hbase.zookeeper.quorum",  
  49.                 "192.168.1.100:2181,192.168.1.101:2181,192.168.1.103:2181");  
  50.     }  
  51.   
  52.     /** 
  53.      * 根据随机散列(hash)创建分区表 
  54.      *  
  55.      * @throws Exception 
  56.      *             hash_split_table 
  57.      */  
  58.     public static void testHashAndCreateTable(String tableNameTmp,  
  59.             String columnFamily) throws Exception {<p>        // 取随机散列 10 代表 10个分区  
  60.         HashChoreWoker worker = new HashChoreWoker(100000010);  
  61.         byte[][] splitKeys = worker.calcSplitKeys();  
  62.   
  63.         HBaseAdmin admin = new HBaseAdmin(config);  
  64.         TableName tableName = TableName.valueOf(tableNameTmp);  
  65.   
  66.         if (admin.tableExists(tableName)) {  
  67.             try {  
  68.                 admin.disableTable(tableName);  
  69.             } catch (Exception e) {  
  70.             }  
  71.             admin.deleteTable(tableName);  
  72.         }  
  73.   
  74.         HTableDescriptor tableDesc = new HTableDescriptor(tableName);  
  75.         HColumnDescriptor columnDesc = new HColumnDescriptor(  
  76.                 Bytes.toBytes(columnFamily));  
  77.         columnDesc.setMaxVersions(1);  
  78.         tableDesc.addFamily(columnDesc);  
  79.   
  80.         admin.createTable(tableDesc, splitKeys);  
  81.   
  82.         admin.close();  
  83.     }  
  84.   
  85.     /** 
  86.      * @Title: queryData 
  87.      * @Description: 从HBase查询出数据 
  88.      * @author kuang hj 
  89.      * @param tableName 
  90.      *            表名 
  91.      * @param rowkey 
  92.      *            rowkey 
  93.      * @return 返回用户信息的list 
  94.      * @throws Exception 
  95.      */  
  96.     @SuppressWarnings("all")  
  97.     public static ArrayList<String> queryData(String tableName, String rowkey)  
  98.             throws Exception {  
  99.         ArrayList<String> list = new ArrayList<String>();  
  100.         logger.info("开始时间");  
  101.         HTable table = new HTable(config, tableName);  
  102.   
  103.         Get get = new Get(rowkey.getBytes()); // 根据主键查询  
  104.         Result r = table.get(get);  
  105.         logger.info("结束时间");  
  106.         KeyValue[] kv = r.raw();  
  107.         for (int i = 0; i < kv.length; i++) {  
  108.             // 循环每一列  
  109.             String key = kv[i].getKeyString();  
  110.               
  111.             String value = kv[i].getValueArray().toString();  
  112.               
  113.             // 将查询到的结果写入List中  
  114.             list.add(key + ":"+ value);  
  115.               
  116.         }// end of 遍历每一列  
  117.           
  118.         return list;  
  119.     }  
  120.   
  121.     /** 
  122.      * 增加表数据 
  123.      *  
  124.      * @param tableName 
  125.      * @param rowkey 
  126.      */  
  127.     public static void insertData(String tableName, String rowkey) {  
  128.         HTable table = null;  
  129.         try {  
  130.             table = new HTable(config, tableName);  
  131.             // 一个PUT代表一行数据,再NEW一个PUT表示第二行数据,每行一个唯一的ROWKEY,此处rowkey为put构造方法中传入的值  
  132.             for (int i = 1; i < 100; i++) {  
  133.                 byte[] result = getNumRowkey(rowkey,i);  
  134.                 Put put = new Put(result);  
  135.                 // 本行数据的第一列  
  136.                 put.add(rowkey.getBytes(), "name".getBytes(),  
  137.                         ("aaa" + i).getBytes());  
  138.                 // 本行数据的第三列  
  139.                 put.add(rowkey.getBytes(), "age".getBytes(),  
  140.                         ("bbb" + i).getBytes());  
  141.                 // 本行数据的第三列  
  142.                 put.add(rowkey.getBytes(), "address".getBytes(),  
  143.                         ("ccc" + i).getBytes());  
  144.   
  145.                 table.put(put);  
  146.             }  
  147.   
  148.         } catch (Exception e1) {  
  149.             e1.printStackTrace();  
  150.         }  
  151.     }  
  152.   
  153.     private static byte[] getNewRowkey(String rowkey) {  
  154.         byte[] result = null;  
  155.   
  156.         RowKeyGenerator rkGen = new HashRowKeyGenerator();  
  157.         byte[] splitKeys = rkGen.nextId();  
  158.   
  159.         byte[] rowkeytmp = rowkey.getBytes();  
  160.   
  161.         result = new byte[splitKeys.length + rowkeytmp.length];  
  162.         System.arraycopy(splitKeys, 0, result, 0, splitKeys.length);  
  163.         System.arraycopy(rowkeytmp, 0, result, splitKeys.length,  
  164.                 rowkeytmp.length);  
  165.   
  166.         return result;  
  167.     }  
  168.       
  169.     public static void main(String[] args) {  
  170.         RowKeyGenerator rkGen = new HashRowKeyGenerator();  
  171.         byte[] splitKeys = rkGen.nextId();  
  172.         System.out.println(splitKeys);      
  173.     }  
  174.   
  175.     private static byte[] getNumRowkey(String rowkey, int i) {  
  176.         byte[] result = null;  
  177.   
  178.         RowKeyGenerator rkGen = new HashRowKeyGenerator();  
  179.         byte[] splitKeys = rkGen.nextId();  
  180.   
  181.         byte[] rowkeytmp = rowkey.getBytes();  
  182.   
  183.         byte[] intVal = BitUtils.getByteByInt(i);  
  184.         result = new byte[splitKeys.length + rowkeytmp.length + intVal.length];  
  185.         System.arraycopy(splitKeys, 0, result, 0, splitKeys.length);  
  186.         System.arraycopy(rowkeytmp, 0, result, splitKeys.length,  
  187.                 rowkeytmp.length);  
  188.         System.arraycopy(intVal, 0, result, splitKeys.length+rowkeytmp.length,  
  189.                 intVal.length);  
  190.   
  191.         return result;  
  192.     }  
  193.       
  194.       
  195.   
  196.     /** 
  197.      * 删除表 
  198.      *  
  199.      * @param tableName 
  200.      */  
  201.     public static void dropTable(String tableName) {  
  202.         try {  
  203.             HBaseAdmin admin = new HBaseAdmin(config);  
  204.             admin.disableTable(tableName);  
  205.             admin.deleteTable(tableName);  
  206.         } catch (MasterNotRunningException e) {  
  207.             e.printStackTrace();  
  208.         } catch (ZooKeeperConnectionException e) {  
  209.             e.printStackTrace();  
  210.         } catch (IOException e) {  
  211.             e.printStackTrace();  
  212.         }  
  213.     }  
  214.   
  215.     /** 
  216.      * 查询所有 
  217.      *  
  218.      * @param tableName 
  219.      */  
  220.     public static void QueryAll(String tableName) {  
  221.         HTable table  = null;  
  222.         try {  
  223.             table  = new HTable(config, tableName);  
  224.             ResultScanner rs = table.getScanner(new Scan());  
  225.             for (Result r : rs) {  
  226.                 System.out.println("获得到rowkey:" + new String(r.getRow()));  
  227.                 for (KeyValue keyValue : r.raw()) {  
  228.                     System.out.println("列:" + new String(keyValue.getFamily())  
  229.                             + "====值:" + new String(keyValue.getValue()));  
  230.                 }  
  231.             }  
  232.         } catch (IOException e) {  
  233.             e.printStackTrace();  
  234.         }  
  235.     }  
  236.   
  237.     /** 
  238.      * 查询所有 
  239.      *  
  240.      * @param tableName 
  241.      */  
  242.     public static void QueryByCondition1(String tableName) {  
  243.   
  244.         HTable table = null;  
  245.         try {  
  246.             table  = new HTable(config, tableName);  
  247.             Get scan = new Get("abcdef".getBytes());// 根据rowkey查询  
  248.             Result r = table.get(scan);  
  249.             System.out.println("获得到rowkey:" + new String(r.getRow()));  
  250.             for (KeyValue keyValue : r.raw()) {  
  251.                 System.out.println("列:" + new String(keyValue.getFamily())  
  252.                         + "====值:" + new String(keyValue.getValue()));  
  253.             }  
  254.         } catch (IOException e) {  
  255.             e.printStackTrace();  
  256.         }  
  257.     }  
  258.       
  259.     /** 
  260.      *  根据rowkwy前坠查询  
  261.      * @param tableName 
  262.      * @param rowkey 
  263.      */  
  264.     public static void queryByRowKey(String tableName,String rowkey)  
  265.     {  
  266.         try {  
  267.             HTable table = new HTable(config, tableName);  
  268.             Scan scan = new Scan();  
  269.             scan.setFilter(new PrefixFilter(rowkey.getBytes()));  
  270.             ResultScanner rs = table.getScanner(scan);  
  271.             KeyValue[] kvs = null;  
  272.             for (Result tmp : rs)  
  273.             {  
  274.                 kvs = tmp.raw();  
  275.                 for (KeyValue kv : kvs)  
  276.                 {  
  277.                     System.out.print(kv.getRow()+" ");  
  278.                     System.out.print(kv.getFamily()+" :");  
  279.                     System.out.print(kv.getQualifier()+" ");  
  280.                     System.out.print(kv.getTimestamp()+" ");  
  281.                     System.out.println(kv.getValue());  
  282.                 }  
  283.             }  
  284.         } catch (IOException e) {  
  285.             e.printStackTrace();  
  286.         }  
  287.           
  288.     }  
  289.     /** 
  290.      * 查询所有 
  291.      *  
  292.      * @param tableName 
  293.      */  
  294.     public static void QueryByCondition2(String tableName) {  
  295.   
  296.         try {  
  297.             HTable table = new HTable(config, tableName);  
  298.             // 当列column1的值为aaa时进行查询  
  299.             Filter filter = new SingleColumnValueFilter(  
  300.                     Bytes.toBytes("column1"), null, CompareOp.EQUAL,  
  301.                     Bytes.toBytes("aaa"));   
  302.             Scan s = new Scan();  
  303.             s.setFilter(filter);  
  304.             ResultScanner rs = table.getScanner(s);  
  305.             for (Result r : rs) {  
  306.                 System.out.println("获得到rowkey:" + new String(r.getRow()));  
  307.                 for (KeyValue keyValue : r.raw()) {  
  308.                     System.out.println("列:" + new String(keyValue.getFamily())  
  309.                             + "====值:" + new String(keyValue.getValue()));  
  310.                 }  
  311.             }  
  312.         } catch (Exception e) {  
  313.             e.printStackTrace();  
  314.         }  
  315.   
  316.     }  
  317.   
  318.     /** 
  319.      * 查询所有 
  320.      *  
  321.      * @param tableName 
  322.      */  
  323.     public static void QueryByCondition3(String tableName) {  
  324.   
  325.         try {  
  326.               
  327.             HTable table = new HTable(config, tableName);  
  328.   
  329.             List<Filter> filters = new ArrayList<Filter>();  
  330.   
  331.             Filter filter1 = new SingleColumnValueFilter(  
  332.                     Bytes.toBytes("column1"), null, CompareOp.EQUAL,  
  333.                     Bytes.toBytes("aaa"));  
  334.             filters.add(filter1);  
  335.   
  336.             Filter filter2 = new SingleColumnValueFilter(  
  337.                     Bytes.toBytes("column2"), null, CompareOp.EQUAL,  
  338.                     Bytes.toBytes("bbb"));  
  339.             filters.add(filter2);  
  340.   
  341.             Filter filter3 = new SingleColumnValueFilter(  
  342.                     Bytes.toBytes("column3"), null, CompareOp.EQUAL,  
  343.                     Bytes.toBytes("ccc"));  
  344.             filters.add(filter3);  
  345.   
  346.             FilterList filterList1 = new FilterList(filters);  
  347.   
  348.             Scan scan = new Scan();  
  349.             scan.setFilter(filterList1);  
  350.             ResultScanner rs = table.getScanner(scan);  
  351.             for (Result r : rs) {  
  352.                 System.out.println("获得到rowkey:" + new String(r.getRow()));  
  353.                 for (KeyValue keyValue : r.raw()) {  
  354.                     System.out.println("列:" + new String(keyValue.getFamily())  
  355.                             + "====值:" + new String(keyValue.getValue()));  
  356.                 }  
  357.             }  
  358.             rs.close();  
  359.   
  360.         } catch (Exception e) {  
  361.             e.printStackTrace();  
  362.         }  
  363.   
  364.     }  
  365. }</p>  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. HashChoreWoker:  
  2.   
  3. import java.util.Iterator;  
  4. import java.util.TreeSet;  
  5.   
  6. import org.apache.hadoop.hbase.util.Bytes;  
  7.   
  8. /** 
  9.  *  
  10.  * @author kuang hj 
  11.  * 
  12.  */  
  13. public class HashChoreWoker{  
  14.     // 随机取机数目  
  15.     private int baseRecord;  
  16.     // rowkey生成器  
  17.     private RowKeyGenerator rkGen;  
  18.     // 取样时,由取样数目及region数相除所得的数量.  
  19.     private int splitKeysBase;  
  20.     // splitkeys个数  
  21.     private int splitKeysNumber;  
  22.     // 由抽样计算出来的splitkeys结果  
  23.     private byte[][] splitKeys;  
  24.   
  25.     public HashChoreWoker(int baseRecord, int prepareRegions) {  
  26.         this.baseRecord = baseRecord;  
  27.         // 实例化rowkey生成器  
  28.         rkGen = new HashRowKeyGenerator();  
  29.         splitKeysNumber = prepareRegions - 1;  
  30.         splitKeysBase = baseRecord / prepareRegions;  
  31.     }  
  32.   
  33.     public byte[][] calcSplitKeys() {  
  34.         splitKeys = new byte[splitKeysNumber][];  
  35.         // 使用treeset保存抽样数据,已排序过  
  36.         TreeSet<byte[]> rows = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);  
  37.         for (int i = 0; i < baseRecord; i++) {  
  38.             rows.add(rkGen.nextId());  
  39.         }  
  40.         int pointer = 0;  
  41.         Iterator<byte[]> rowKeyIter = rows.iterator();  
  42.         int index = 0;  
  43.         while (rowKeyIter.hasNext()) {  
  44.             byte[] tempRow = rowKeyIter.next();  
  45.             rowKeyIter.remove();  
  46.             if ((pointer != 0) && (pointer % splitKeysBase == 0)) {  
  47.                 if (index < splitKeysNumber) {  
  48.                     splitKeys[index] = tempRow;  
  49.                     index++;  
  50.                 }  
  51.             }  
  52.             pointer++;  
  53.         }  
  54.         rows.clear();  
  55.         rows = null;  
  56.         return splitKeys;  
  57.     }  
  58. }  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. HashRowKeyGenerator:  
  2. import org.apache.hadoop.hbase.util.Bytes;  
  3. import org.apache.hadoop.hbase.util.MD5Hash;  
  4.   
  5. import com.kktest.hbase.BitUtils;  
  6. /** 
  7. * 
  8. * 
  9. **/  
  10. public class HashRowKeyGenerator implements RowKeyGenerator {  
  11.     private static long currentId = 1;  
  12.     private static long currentTime = System.currentTimeMillis();  
  13.     //private static Random random = new Random();  
  14.   
  15.     public byte[] nextId()   
  16.     {  
  17.         try {  
  18.             currentTime = getRowKeyResult(Long.MAX_VALUE - currentTime);  
  19.             byte[] lowT = Bytes.copy(Bytes.toBytes(currentTime), 44);  
  20.             byte[] lowU = Bytes.copy(Bytes.toBytes(currentId), 44);  
  21.             byte[] result = Bytes.add(MD5Hash.getMD5AsHex(Bytes.add(lowT, lowU))  
  22.                     .substring(08).getBytes(), Bytes.toBytes(currentId));  
  23.             return result;  
  24.         } finally {  
  25.             currentId++;  
  26.         }  
  27.     }  
  28.       
  29.     /** 
  30.      *  getRowKeyResult 
  31.      * @param tmpData 
  32.      * @return 
  33.      */  
  34.     public static long getRowKeyResult(long tmpData)  
  35.     {  
  36.         String str = String.valueOf(tmpData);  
  37.         StringBuffer sb = new StringBuffer();  
  38.         char[] charStr = str.toCharArray();  
  39.         for (int i = charStr.length -1 ; i > 0; i--)  
  40.         {  
  41.             sb.append(charStr[i]);  
  42.         }  
  43.           
  44.         return Long.parseLong(sb.toString());  
  45.     }  
  46. }  




[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. </pre><pre name="code" class="java">  
0 0
原创粉丝点击