1006-HBase操作實戰(JAVA API模式)

來源:互聯網
上載者:User

標籤:hbase

一、準備階段開發環境: hadoophadoop -2.4.0 hbasehbase -0.94.11-securityeclipse:Juno Service Release 2
二、建立  hbasedemo項目
1、通過 Eclipse 建立一個新 Java 工程2、右擊項目根目錄,選擇“Propertiesà> Java Build Pathà> Libraryà>  Add  External  JARs”3、添加jar檔案到  classpath3.1 解壓 HBase 安裝檔案3.2 拷貝  hbase-0.94.7-security.jar、  hbase-0.94.11-security-tests.jar到工程3.3  lib 子目錄下所有的 jar 包添加到本工程的 Build Path下
三、使用HBase JAVA API
初始化和釋放資源方法:
public void init() 資料初始化
public void destory()  釋放資源

驗證方法:
public void testCreate() 驗證建立表
public void testDrop() 驗證刪除表
public void testPut()驗證添加表資料
public void testGetByRowKey() 驗證如何通過rowkey擷取資料
public void testScanSToEnd() 驗證範圍行資料擷取
public void testScanAll()  驗證全表掃描

方法:
public List<Cell> get(String tableName, String rowKey)  通過rowKey插入表資料
public List<Result> scan(String tableName)  通過表名查詢所有資訊
public List<Result> scan(String tableName,String startRow,String stopRow) 查詢範圍行方法
public void create(String tableName, String[] cfs)  通過表名和列族資訊建立表
public void drop(String tableName) 刪除表
public void put(String tableName, List<CellBean> values) 根據提供的表和對象資訊插入hbase

第一步: 封裝HBase中的儲存單元Cell對象

/** * 封裝HBase中儲存單元cell對象 * @author shenfl * @version:V1.0 * @Date:2015-6-8 */public class CellBean {//行健private String rowKey;//列族private String columnFamilly;//列名private String columnName;//cell值private String columnValue;public String getRowKey() {return rowKey;}public void setRowKey(String rowKey) {this.rowKey = rowKey;}public String getColumnFamilly() {return columnFamilly;}public void setColumnFamilly(String columnFamilly) {this.columnFamilly = columnFamilly;}public String getColumnName() {return columnName;}public void setColumnName(String columnName) {this.columnName = columnName;}public String getColumnValue() {return columnValue;}public void setColumnValue(String columnValue) {this.columnValue = columnValue;}}

第二步: 使用HBase JAVA API 操作HBase  資料庫
/** * 使用HBase JAVA API操作 * * @author shenfl * */public class HBaseTest {    Configuration config = null ;    // 建立動作表對象    HBaseAdmin admin = null;    // hbase的串連    HConnection conn = null;    @Before    public void init() {          config = HBaseConfiguration. create();          // HBase只需要知道ZooKeeper,就可以操作RegionServer上的數據,設定HBase 串連ZooKeeper          config.set( "hbase.zookeeper.quorum" , "192.168.2.35:2181,192.168.2.36:2181,192.168.2.37:2181" );          try {              conn = HConnectionManager.createConnection( config);              admin = new HBaseAdmin(config );         } catch (Exception e ) {              e.printStackTrace();         }    }    @After    public void destory() {          try {              admin.close();         } catch (IOException e ) {              e.printStackTrace();         }    }    @Test    public void testCreate() {         String tableName = "account" ;         String[] columnFamilies = new String[] { "info" , "other" };         create( tableName , columnFamilies );    }    //@Test    public void testDrop() {         drop( "account" );    }    @Test    public void testPut() {          // 設定表對象列表         List<CellBean> cbList = new ArrayList<CellBean>();          // 設定表名account         String tableName = "account" ;         CellBean e = null ;          for (int i =0;i <3;i ++){              e = new CellBean();              e.setRowKey( "g20142500" +i );              e.setColumnFamilly( "info" );              e.setColumnName( "username" );              e.setColumnValue( "shenfl" +i );              cbList.add( e);              e = new CellBean();              e.setRowKey( "g20142500" +i );              e.setColumnFamilly( "other" );              e.setColumnName( "career" );              e.setColumnValue( "singer" +i );              cbList.add( e);         }         put( tableName , cbList );    }    @Test    public void testGetByRowKey() {                  String tableName = "account" ;         String rowKey = "g201425001" ;         List<Cell> cells = get( tableName , rowKey );         StringBuffer info = new StringBuffer();          for (Cell c : cells ) {              //使用CellUtil方法輸出對應列, hbase0.96 版本使用CellUtil函數              info.append( new String(CellUtil.cloneFamily(c))).append( ":" )                 .append( new String(CellUtil.cloneQualifier(c))).append( "\t" )                 .append( new String(CellUtil.cloneValue(c))).append( "\n" );         }         System. out .println(info );    }    @Test    public void testScanSToEnd(){                  StringBuffer sb = new StringBuffer();         String tableName = "account" ;         String startRow = "g201425000" ;         String stopRow = "g201425002" ;         List<Result> rsList = scan( tableName , startRow , stopRow );          byte [] rowKey = null;          byte [] username = null;          byte [] career = null;          for (Result rs :rsList ){              rowKey = rs.getRow();              username = rs .getValue(Bytes.toBytes( "info" ), Bytes.toBytes("username"));              career = rs .getValue(Bytes.toBytes( "other" ), Bytes.toBytes("career"));              sb.append( new String(rowKey )).append("\t" )               .append( new String(username )).append("\t" )               .append( new String(career )).append("\n" );         }         System. out .println(sb .toString());    }        @Test    public void testScanAll() {         StringBuffer sb = new StringBuffer();         List<Result> rsList = scan( "account" );          for (Result rs : rsList ) {             List<Cell> listCells = rs .listCells();              for (Cell c : listCells ) {                  // 使用CellUtil方法輸出對應列, hbase0.96 版本使用CellUtil函數                  sb.append( new String(CellUtil.cloneRow(c))).append( "\t" )                   .append( new String(CellUtil.cloneFamily(c))).append( ":" )                   .append( new String(CellUtil.cloneQualifier(c))).append( "\t" )                   .append( new String(CellUtil.cloneValue(c))).append( "\n" );             }         }         System. out .println(sb );    }    /**     * 通過rowKey插入表資料     * @param tableName 表名     * @param rowKey 行健     * @return     */    public List<Cell> get(String tableName , String rowKey ) {         HTableInterface table = null ;         Get get = null ;         Result rs = null ;         List<Cell> listCells = new ArrayList<Cell>();          try {              table = conn.getTable( tableName );              get = new Get(Bytes.toBytes( rowKey));              rs = table.get( get);              listCells = rs .listCells();         } catch (IOException e ) {              e.printStackTrace();         }          return   listCells ;    }        /**     * 查詢所有行     *     * @param tableName     * @return     */    public List<Result> scan(String tableName ) {         HTableInterface table = null ;         List<Result> rsList = new ArrayList<Result>();          try {              table = conn.getTable( tableName );             Scan scan = new Scan();             ResultScanner scanner = table .getScanner(scan );             Iterator<Result> iterator = scanner .iterator();             Result rs = null ;              while (iterator .hasNext()) {                  rs = (Result) iterator.next();                  rsList.add( rs);             }         } catch (Exception e ) {              e.printStackTrace();         }          return rsList ;    }    /**     * 查詢範圍行     * @param tableName 表名     * @param startRow  開始的行健     * @param stopRow   結束行健     * @return     */    public List<Result> scan(String tableName ,String startRow ,String stopRow ) {                  HTableInterface table = null ;         List<Result> rsList = new ArrayList<Result>();          try {              table = conn.getTable( tableName );             Scan scan = new Scan();              scan.setStartRow(Bytes. toBytes(startRow));              scan.setStopRow(Bytes. toBytes(stopRow));             ResultScanner rs = table .getScanner(scan );                           for (Result v :rs ){                  rsList.add( v);             }         } catch (Exception e ) {              e.printStackTrace();         }          return   rsList ;    }    /**     * 建立壁報     *     * @param tableName     *            表名     * @param cfs     *            列族     */    public void create(String tableName , String[] cfs ) {          if (cfs == null || cfs.length == 0) {              return ;         }          try {              // 校正表是否儲存              if (admin .tableExists(tableName)) {                  return ;             }              // 建立表             HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));              // 建立列族              for (String cf : cfs ) {                  desc.addFamily( new HColumnDescriptor(cf ));             }              // 建立表              admin.createTable( desc);         } catch (IOException e ) {              e.printStackTrace();         }    }    /**     * 刪除表     *     * @param tableName     *            表名     */    public void drop(String tableName ) {          try {              if (admin .tableExists(tableName)){                                   admin.disableTable( tableName );                  admin.deleteTable( tableName );             }         } catch (IOException e ) {              e.printStackTrace();         }    }    /**     * 向指定表插入資料     *     * @param tableName     *            表名     * @param values     *            資料     */    public void put(String tableName , List<CellBean> values ) {          if (StringUtils.isBlank( tableName ) || values == null || values .size() == 0) {              return ;         }         Put put = null ;         HTableInterface table = null ;          try {              table = conn.getTable( tableName );              for (CellBean v : values ) {                  put = new Put(Bytes.toBytes(v.getRowKey()));                  put.add(Bytes. toBytes(v.getColumnFamilly()), Bytes.toBytes(v.getColumnName()),                          Bytes. toBytes(v.getColumnValue()));                  table.put( put);             }         } catch (Exception e ) {              // 實際生產環境要通過記錄日誌,例如: logger.warn("xxxxx",e);              e.printStackTrace();         }    }}




參考文章:1、HBase串連池 -- HTablePool被Deprecated之後http://blog.csdn.net/u010967382/article/details/380468212、HBase Java API 介紹http://www.cnblogs.com/NicholasLee/archive/2012/09/13/2683432.html3、HBase Java API 操作案例http://www.programcreek.com/java-api-examples/index.php?api=org.apache.hadoop.hbase.HTableDescriptorhttp://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Admin.htmlhttp://blog.csdn.net/hadoop_/article/details/11481215

1006-HBase操作實戰(JAVA API模式)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.