Hbase Java API

Source: Internet
Author: User

This article uses the most primitive Java APIs, not using Spring-data-hbase, but using spring to manage HBase's configuration
The query operation is divided into the following steps: 1. Gets the HBase configuration, where the configuration primarily refers to the address of hbase. If zookeeper is managed, you can use the Zookeeper address and Port 2. Get HBase connections based on configuration:
= ConnectionFactory. createconnection (this.) hbaseconfig. Gethbaseconfiguration ())
3. Under HBase connection, get htable.
Htable htable = (htable) connection.gettable (TableName.  ValueOf(tableName));
4. Inquiries. Multi-line query (scan mode) and single row query (get mode) sample code for scan mode


Scan.setstartrow (Bytes.tobytes(StartRow));  Scan.setstoprow (Bytes.tobytes(Endrow));  Scan.setcaching (4000);  Scan.setbatch (3);  //Set column family//Scan.addfamily (Bytes.tobytes (columnfamily));//Set column Scan.addcolumn (Bytes.tobytes(columnfamily), Bytes.tobytes("Createtime"));  Scan.addcolumn (Bytes.tobytes(columnfamily), Bytes.tobytes("Lat"));  Scan.addcolumn (Bytes.tobytes(columnfamily), Bytes.tobytes("Lon"));
5. Get query data, take scan as an example
Resultscanner = Htable.getscanner (scan);

6. Get the data in the cell


for (Result result:resultscanner) {    Rwwdata rwwdata = new Rwwdata ();  for (cell cell:result.rawCells ()) {        String k = bytes.tostring (Cellutil.clonequalifier (cell));  String v = bytes.tostring (Cellutil.clonevalue (cell));    } }





which
Cellutil. Clonequalifier (cell)
Gets the name of each column.
Cellutil. Clonevalue (cell)
Gets the value that corresponds to the name of each column.

Hbaseconfig


public class Hbaseconfig {private static String zookeeperaddr = "";    private static String Zookeeperpoot = "2181";    private static int zkretry = 2;    private static Configuration hbaseconfiguration = null;            static {if (hbaseconfiguration = = null) {Configuration configuration = new configuration ();            Configuration.set ("Hbase.zookeeper.quorum", zookeeperaddr);            Configuration.set ("Hbase.zookeeper.property.clientPort", zookeeperpoot);            Configuration.setint ("Hbase.client.retries.number", zkretry);        Hbaseconfiguration = hbaseconfiguration.create (configuration);    }} public static Configuration gethbaseconfiguration () {return hbaseconfiguration;    } public void Setzookeeperaddr (String zookeeperaddr) {this.zookeeperaddr = zookeeperaddr;    } public void Setzookeeperpoot (String zookeeperpoot) {this.zookeeperpoot = Zookeeperpoot; } public void Setzkretry (int zkretry) {thIs.zkretry = Zkretry; }}




Hbaseconnection


public class Hbaseconnection {    private static Connection Connection = null;    private static Hbaseconfig hbaseconfig;    static {        if (connection = = null) {            try {                connection = connectionfactory.createconnection ( Hbaseconfig.gethbaseconfiguration ());            } catch (IOException e) {                e.printstacktrace ();}}    }    public static Connection getconnection () {        return Connection;    }    public void Sethbaseconfig (Hbaseconfig hbaseconfig) {        this.hbaseconfig = Hbaseconfig;    }}





Hbaseservice


public class Hbaseservice {private Logger Logger = Loggerfactory.getlogger (Hbaseservice.class);    Private final long BASE = 2147483647;    Private Hbaseconnection hbaseccnnection;     /** * @param tableName: Table name * @param columnfamily: Column family * @param phone: Mobile number * @param beginTime: Query start time * @param endTime: Query End time * @return * @throws ioexception * * Public list<geopoint> getgeopoints (FINA L string tableName, final string columnfamily, String phone, long beginTime, long endTime) throws I  Oexception, InvocationTargetException, Illegalaccessexception, parseexception {list<geopoint> geoPointList =        New Arraylist<> ();        Connection Connection = Hbaseconnection.getconnection ();        Htable htable = (htable) connection.gettable (tablename.valueof (TableName));        Build Scan Scan scan = new scan ();        String StartRow = This.getrowkey (phone, endTime); String Endrow = This.getrowkey (phone, beGintime);        System.out.println (StartRow + ":" + Endrow);        Scan.setstartrow (Bytes.tobytes (StartRow));        Scan.setstoprow (Bytes.tobytes (Endrow));        Scan.setcaching (4000);        Scan.setbatch (3);        Set column family//scan.addfamily (Bytes.tobytes (columnfamily));        Set Column Scan.addcolumn (Bytes.tobytes (columnfamily), Bytes.tobytes ("Createtime"));        Scan.addcolumn (Bytes.tobytes (columnfamily), bytes.tobytes ("lat"));        Scan.addcolumn (Bytes.tobytes (columnfamily), Bytes.tobytes ("Lon"));        Resultscanner resultscanner = null;        list<rwwdata> rowdatalist = new arraylist<> ();            Get coordinate point try {resultscanner = Htable.getscanner (scan);                for (result Result:resultscanner) {System.out.println ("Result:" + result);                Rwwdata rwwdata = new Rwwdata ();                System.out.println ("Rawcelles" + result.rawcells ());           For (Cell cell:result.rawCells ()) {         String k = bytes.tostring (Cellutil.clonequalifier (cell));                    String v = bytes.tostring (Cellutil.clonevalue (cell));                Rwwdata.set (k, v);                } System.out.println (Rwwdata);            Rowdatalist.add (Rwwdata);            }} catch (Exception e) {logger.error ("error getting coordinate point information from HBase", e);        E.printstacktrace ();        } finally {resultscanner.close ();        } System.out.println ("" Rowdatalist: "" + rowdatalist.size ());        System.out.println (rowdatalist);            if (rowdatalist.size () > 0) {//Sort Collections.sort (rowdatalist) in ascending order of time;            System.out.println ("rowdatalist Sort:" "+ rowdatalist);//GeoPoint GeoPoint = new GeoPoint (); for (Rwwdata rwwdata:rowdatalist) {GeoPoint GeoPoint = new GeoPoint ();//BEANUTILS.COPYPR                Operties (GeoPoint, rwwdata); Geopoint.x = Rwwdata.lat;Dimension geopoint.y = Rwwdata.lon;            Longitude Geopointlist.add (geoPoint);        }} System.out.println (Geopointlist);    return geopointlist; }/** * phone+ (2147483647-specified time in seconds) * * @param phone * @param times * @return * @throws PARSEEXCEP tion */private string Getrowkey (string phone, long time) throws ParseException {//Long Phonenum = Numberut Ils.tolong (phone);//SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");//Long Timemills        Econds = Format.parse (time). GetTime (); Long result = this.        base-time/1000;    return phone + result;        }/** * */Private class Rwwdata implements comparable<rwwdata> {private String createtime; Private double lat; Dimension, lat private double lon; Longitude, lon//can use reflection Ah, with the simplest public void set (string k, String value) throws Nosuchfieldexception, Illegalaccesse xception {PReconditions.checkargument (Stringutils.isnotblank (k));            Preconditions.checkargument (value! = null);            Field f = RwwData.class.getDeclaredField (k);            F.setaccessible (TRUE); F.set (this, value);//if (Stringutils.equals ("Createtime", K)) {//This.createtime = String.valu EOf (value),//} else if (Stringutils.equals ("lat", K)) {//this.x = double.parsedouble (value);            /dimension//} else if (Stringutils.equals ("Lon", K)) {//This.y = double.parsedouble (value);//Longitude//        } else {//throw new IllegalArgumentException ("No properties" + K + "found");/} } @Override public int compareTo (Rwwdata o) {return this.createtime.compareTo (o.createtime)        ;        } public double Getlon () {return lon;        } public void Setlon (double lon) {This.lon = lon; } public Double Getlat () {return lat;        } public void Setlat (double lat) {This.lat = lat;        } public String Getcreatetime () {return createtime;        } public void Setcreatetime (String createtime) {this.createtime = Createtime; } @Override Public String toString () {return ' rwwdata{' + ' createtime= ' + CR        Eatetime + ' + ' + ', lat= "+ Lat +", lon= "+ Lon + '} ';        }} public class GeoPoint {private Double X;        private double y;        Private double XYY;        Private double yx;        Private String Fyx;        Public double GetX () {return x;        public void SetX (double x) {this.x = x;        } public double GetY () {return y;        public void sety (double y) {this.y = y; } public double Getxyy () {RETurn XYY;        } public void Setxyy (double xyy) {this.xyy = XYY;        } public double Getyx () {return yx;        } public void Setyx (double yx) {this.yx = YX;        } public String Getfyx () {return fyx;        } public void Setfyx (String fyx) {this.fyx = Fyx;                    } @Override Public String toString () {return "geopoint{" + "x=" + x +        ", y=" + y + '} '; }    }}






Hbase Java API

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.