1006-hbase operation Combat (JAVA API mode)

Source: Internet
Author: User
Tags zookeeper

first, the preparatory stageDevelopment Environment: Hadoop : hadoop -2.4.0 hbase : hbase -0.94.11-security Eclipse:juno Service Release 2
ii. Creation of Hbasedemo Project
1. Create a new Java project from Eclipse2. Right-click the project root directory and select "Propertiesà> Java Build pathà> libraryà> Add External JARs" 3. Add jar file to classpath 3.1 Unpacking the HBase installation file 3.2 Copy hbase-0.94.7-security.jar, hbase- 0.94.11-security-tests.jar to Engineering all jar packages under the 3.3 lib subdirectory are added to the project's Build path
Iii. using the hbase JAVA API
Initialize and dispose of resource methods:
public void init () data initialization
public void destory ()   Free resources

Authentication method:
public void testcreate () Validation create TABLE
public void Testdrop () Verify delete table
public void Testput () Validate Add table data
public void Testgetbyrowkey () Verify how to get data through Rowkey
public void Testscanstoend () validation range row data get
public void Testscanall ()   Verify full table Scan

Method:
Public list<cell> Get (string tableName, string rowKey)   Insert table data through RowKey
public list <Result> Scan (string tableName)   Querying all information by table name
Public list<result> Scan (string tablename,string Startrow,string stoprow) Query range row method
public void Create (String tableName, string[] cfs)   CREATE table by table name and column family information
Public void Drop (string tableName) Delete table
public void put (string tableName, list<cellbean> values) insert hbase based on provided table and object information

First step: Encapsulate a storage cell in HBase Cell object

/** * Encapsulates the storage cell object in HBase * @author SHENFL * @version: V1.0 * @Date: 2015-6-8 */public class Cellbean {//Line Jian private String row key;//column Family private string columnfamilly;//column name private string Columnname;//cell value 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;}}

Step Two: Use the HBase JAVA API to manipulate the HBase database
/** * operation with hbase JAVA API * * @author SHENFL * */public class Hbasetest {Configuration config = null;    Create action table to hbaseadmin admin = null;    The connection of hbase hconnection conn = null;          @Before public void init () {config = hbaseconfiguration. Create (); HBase just need to know zookeeper, you can manipulate the regionserver on the numbers, set the HBase connection 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 () {//Set Table object list list<cellbean> cblist = new arraylist<cellbean&          gt; ();         Set table name 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) {//using the Cellutil method to output the corresponding column, the hbase0.96 version uses the Cellutil function Info.append (The new String (Ce                 Llutil.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"). A         Ppend (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) {//Use the Cellutil method to output the corresponding column, hbase0.96 version uses the Cellutil function sb.append (NE  W 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); /** * Insert Table data through RowKey * @param tableName table name * @param rowKey * @return * */Public list<cell& Gt         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; /** * Query All Lines * * @param tableName * @return * * Public list<result> scan (String Tablen         AME) {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;     }/** * Query range row * @param tableName table name * @param startrow start of the line health * @param stoprow End Line Health * @return */Public list<result> Scan (string tableName, String StartRow, String stoprow) {HTABLEINTERFAC         e 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;  }/** * Create poster * * @param tableName * Table name * @param CFS * Column family */public         void Create (String tableName, string[] cfs) {if (cfs = = NULL | | cfs.length = = 0) {return;             } try {//Verify that the table stores if (admin. tableexists (tableName)) {return;              }//CREATE TABLE Htabledescriptor desc = new Htabledescriptor (tablename.valueof (TableName));             Create a column family for (String Cf:cfs) {desc.addfamily (new hcolumndescriptor (CF));         }//CREATE TABLE admin.createtable (DESC); } catch (IOException e) {E.printStackTrace ();          }}/** * Delete table * * @param tableName * Table name */public void Drop (String tableName) { try {if (admin. tableexists (tableName)) {admin.disabletable (table                  Name);             Admin.deletetable (TableName);         }} catch (IOException e) {e.printstacktrace ();     }}/** * Insert data into the specified table * * @param tableName * Table name * @param values * data  */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) {//Actual production environment through logging, for example: Logger.warn ("xxxxx", e);         E.printstacktrace (); }    }}




Reference article:1. HBase Connection Pool--htablepool after being deprecatedhttp://blog.csdn.net/u010967382/article/details/380468212. HBase Java API Introductionhttp://www.cnblogs.com/NicholasLee/archive/2012/09/13/2683432.html3. HBase Java API Operation CaseHttp://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 operation Combat (JAVA API mode)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.