HBase Java客户端编程


本文以Hbase-0.92.0为例,介绍如何在Windows系统,Eclipse IDE集成环境下,使用Java语言,进行HBase客户端编程,包含建立表、删除表、插入记录、删除记录、各种方式下的查询操作等。

1. 准备工作

1、下载后安装jdk包;

2、下载eclipse,解压到本地;

3、下载HBase包,解压安装包到本地(这里使用的是 Hbase-0.92.0)。

2. 搭建开发环境

1、运行Eclipse,创建一个新的Java工程“HBaseClient”,右键项目根目录,选择 “Properties”->“Java Build Path”->“Library”->“Add External JARs”,将HBase解压后根目录下的hbase-0.92.0.jar、hbase-0.92.0-tests.jar和lib子目录下所有jar 包添加到本工程的Classpath下。

2、按照步骤1中的操作,将自己所连接的HBase的配置文件hbase-site.xml添加到本工程的Classpath中,如下所示为配置文件的一个示例:

  1. <configuration>   
  2. <property>   
  3. <name>hbase.rootdir</name>   
  4. <value>hdfs://Hadoop-1:9000/hbase</value>   
  5. </property>   
  6. <property>   
  7. <name>hbase.cluster.distributed</name>   
  8. <value>true</value>   
  9. </property>   
  10. <property>   
  11. <name>hbase.zookeeper.quorum</name>   
  12. <value>hadoop-1,hadoop-2,hadoop-3,hadoop-4</value>   
  13. </property>   
  14. <property>   
  15. <name>zookeeper.session.timeout</name>   
  16. <value>60000</value>   
  17. </property>   
  18. <property>   
  19. <name>hbase.master</name>   
  20. <value>hadoop-1:60000</value>   
  21. </property>   
  22. <property>   
  23. <name>hbase.zookeeper.property.clientPort</name>   
  24. <value>21818</value>   
  25. </property>   
  26. </configuration>  

3、下面可以在Eclipse环境下进行HBase编程了。

3. HBase基本操作代码示例

  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.ZooKeeperConnectionException;      
  12. import org.apache.hadoop.hbase.client.Delete;      
  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.Result;      
  17. import org.apache.hadoop.hbase.client.ResultScanner;      
  18. import org.apache.hadoop.hbase.client.Scan;      
  19. import org.apache.hadoop.hbase.client.Put;      
  20. import org.apache.hadoop.hbase.util.Bytes;      
  21.        
  22. public class HBaseTest {        
  23.           
  24.     private static Configuration conf =null;   
  25.      /**  
  26.       * 初始化配置  
  27.      */  
  28.      static {   
  29.          conf = HBaseConfiguration.create();   
  30.      }   
  31.         
  32.     /**    
  33.      * 创建一张表    
  34.      */     
  35.     public static void creatTable(String tableName, String[] familys) throws Exception {      
  36.         HBaseAdmin admin = new HBaseAdmin(conf);      
  37.         if (admin.tableExists(tableName)) {      
  38.             System.out.println("table already exists!");      
  39.         } else {      
  40.             HTableDescriptor tableDesc = new HTableDescriptor(tableName);      
  41.             for(int i=0; i<familys.length; i++){      
  42.                 tableDesc.addFamily(new HColumnDescriptor(familys[i]));      
  43.             }      
  44.             admin.createTable(tableDesc);      
  45.             System.out.println("create table " + tableName + " ok.");      
  46.         }       
  47.     }      
  48.           
  49.     /**    
  50.      * 删除表    
  51.      */     
  52.     public static void deleteTable(String tableName) throws Exception {      
  53.        try {      
  54.            HBaseAdmin admin = new HBaseAdmin(conf);      
  55.            admin.disableTable(tableName);      
  56.            admin.deleteTable(tableName);      
  57.            System.out.println("delete table " + tableName + " ok.");      
  58.        } catch (MasterNotRunningException e) {      
  59.            e.printStackTrace();      
  60.        } catch (ZooKeeperConnectionException e) {      
  61.            e.printStackTrace();      
  62.        }      
  63.     }      
  64.            
  65.     /**    
  66.      * 插入一行记录    
  67.      */     
  68.     public static void addRecord (String tableName, String rowKey, String family, String qualifier, String value)      
  69.             throws Exception{      
  70.         try {      
  71.             HTable table = new HTable(conf, tableName);      
  72.             Put put = new Put(Bytes.toBytes(rowKey));      
  73.             put.add(Bytes.toBytes(family),Bytes.toBytes(qualifier),Bytes.toBytes(value));      
  74.             table.put(put);      
  75.             System.out.println("insert recored " + rowKey + " to table " + tableName +" ok.");      
  76.         } catch (IOException e) {      
  77.             e.printStackTrace();      
  78.         }      
  79.     }      
  80.        
  81.     /**    
  82.      * 删除一行记录    
  83.      */     
  84.     public static void delRecord (String tableName, String rowKey) throws IOException{      
  85.         HTable table = new HTable(conf, tableName);      
  86.         List list = new ArrayList();      
  87.         Delete del = new Delete(rowKey.getBytes());      
  88.         list.add(del);      
  89.         table.delete(list);      
  90.         System.out.println("del recored " + rowKey + " ok.");      
  91.     }      
  92.            
  93.     /**    
  94.      * 查找一行记录    
  95.      */     
  96.     public static void getOneRecord (String tableName, String rowKey) throws IOException{      
  97.         HTable table = new HTable(conf, tableName);      
  98.         Get get = new Get(rowKey.getBytes());      
  99.         Result rs = table.get(get);      
  100.         for(KeyValue kv : rs.raw()){      
  101.             System.out.print(new String(kv.getRow()) + " " );      
  102.             System.out.print(new String(kv.getFamily()) + ":" );      
  103.             System.out.print(new String(kv.getQualifier()) + " " );      
  104.             System.out.print(kv.getTimestamp() + " " );      
  105.             System.out.println(new String(kv.getValue()));      
  106.         }      
  107.     }      
  108.            
  109.     /**    
  110.      * 显示所有数据    
  111.      */     
  112.     public static void getAllRecord (String tableName) {      
  113.         try{      
  114.              HTable table = new HTable(conf, tableName);      
  115.              Scan s = new Scan();      
  116.              ResultScanner ss = table.getScanner(s);      
  117.              for(Result r:ss){      
  118.                  for(KeyValue kv : r.raw()){      
  119.                     System.out.print(new String(kv.getRow()) + " ");      
  120.                     System.out.print(new String(kv.getFamily()) + ":");      
  121.                     System.out.print(new String(kv.getQualifier()) + " ");      
  122.                     System.out.print(kv.getTimestamp() + " ");      
  123.                     System.out.println(new String(kv.getValue()));      
  124.                  }      
  125.              }      
  126.         } catch (IOException e){      
  127.             e.printStackTrace();      
  128.         }      
  129.     }      
  130.           
  131.     public static void  main (String [] agrs) {      
  132.         try {      
  133.             String tablename = "scores";      
  134.             String[] familys = {"grade""course"};      
  135.             HBaseTest.creatTable(tablename, familys);      
  136.                    
  137.             //add record zkb      
  138.             HBaseTest.addRecord(tablename,"zkb","grade","","5");      
  139.             HBaseTest.addRecord(tablename,"zkb","course","","90");      
  140.             HBaseTest.addRecord(tablename,"zkb","course","math","97");      
  141.             HBaseTest.addRecord(tablename,"zkb","course","art","87");      
  142.             //add record  baoniu      
  143.             HBaseTest.addRecord(tablename,"baoniu","grade","","4");      
  144.             HBaseTest.addRecord(tablename,"baoniu","course","math","89");      
  145.                    
  146.             System.out.println("===========get one record========");      
  147.             HBaseTest.getOneRecord(tablename, "zkb");      
  148.                    
  149.             System.out.println("===========show all record========");      
  150.             HBaseTest.getAllRecord(tablename);      
  151.                    
  152.             System.out.println("===========del one record========");      
  153.             HBaseTest.delRecord(tablename, "baoniu");      
  154.             HBaseTest.getAllRecord(tablename);      
  155.                    
  156.             System.out.println("===========show all record========");      
  157.             HBaseTest.getAllRecord(tablename);      
  158.         } catch (Exception e) {      
  159.             e.printStackTrace();      
  160.         }      
  161.     }      
  162. }    

相关内容