HBase(第二节)HBase的JavaAPI、HBase底层原理和HBase的三个重要机制

HBase的JavaAPI

创建maven项目,pom文件如下:

<repositories>
   <repository>
       <id>cloudera</id>
       <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
   </repository>
</repositories>

<dependencies>

   <dependency>
       <groupId>org.apache.hadoop</groupId>
       <artifactId>hadoop-client</artifactId>
       <version>2.6.0-mr1-cdh5.14.0</version>
   </dependency>


   <dependency>
       <groupId>org.apache.hbase</groupId>
       <artifactId>hbase-client</artifactId>
       <version>1.2.0-cdh5.14.0</version>
   </dependency>

   <dependency>
       <groupId>org.apache.hbase</groupId>
       <artifactId>hbase-server</artifactId>
       <version>1.2.0-cdh5.14.0</version>
   </dependency>


   <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <version>4.12</version>
       <scope>test</scope>
   </dependency>
   <dependency>
       <groupId>org.testng</groupId>
       <artifactId>testng</artifactId>
       <version>6.14.3</version>
       <scope>test</scope>
   </dependency>


</dependencies>

<build>
   <plugins>
       <plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-compiler-plugin</artifactId>
           <version>3.0</version>
           <configuration>
               <source>1.8</source>
               <target>1.8</target>
               <encoding>UTF-8</encoding>
               <!--    <verbal>true</verbal>-->
           </configuration>
       </plugin>
       <plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-shade-plugin</artifactId>
           <version>2.2</version>
           <executions>
               <execution>
                   <phase>package</phase>
                   <goals>
                       <goal>shade</goal>
                   </goals>
                   <configuration>
                       <filters>
                           <filter>
                               <artifact>*:*</artifact>
                               <excludes>
                                   <exclude>META-INF/*.SF</exclude>
                                   <exclude>META-INF/*.DSA</exclude>
                                   <exclude>META-INF/*/RSA</exclude>
                               </excludes>
                           </filter>
                       </filters>
                   </configuration>
               </execution>
           </executions>
       </plugin>
   </plugins>
</build>

代码

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HbaseOpera
{
    private Connection connection;
    private Table table;

	/*
	连接HBase
	*/
    @BeforeTest
    public void init() throws IOException
    {
        //连接到Hbase
        Configuration configuration= HBaseConfiguration.create();
        configuration.set("hbase.rootdir","hdfs://node01:8020/hbase");
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        configuration.set("hbase.zookeeper.quorum","node01,node02,node03");
        //configuration.set("hbase.master","node01:16000");

        connection=ConnectionFactory.createConnection(configuration);
    }

	/*
	创建HBase表
	*/
    @Test
    public void createTable() throws IOException
    {
        //获取管理员的对象,这个对象就是用于创建表,删除表等等
        Admin admin = connection.getAdmin();
        //定义一个Hbase表和它的表名
        HTableDescriptor hTableDescriptor=new HTableDescriptor(TableName.valueOf("myuser"));
        //对表添加列族
        hTableDescriptor.addFamily(new HColumnDescriptor("f1"));
        hTableDescriptor.addFamily(new HColumnDescriptor("f2"));
        //创建表
        admin.createTable(hTableDescriptor);

        admin.close();
    }
    
	/*
	插入数据
	*/
    @Test
    public void addData() throws IOException
    {
        //获取表
        table=connection.getTable(TableName.valueOf("myuser"));
        //创建一个数据行
        Put put=new Put("0001".getBytes());
        //向数据行指定的列族添加名为name的列和值
        put.addColumn("f1".getBytes(),"name".getBytes(),"lisi".getBytes());
        //向数据行指定的列族添加名为age的列和值
        put.addColumn("f1".getBytes(),"age".getBytes(), Bytes.toBytes(25));
        //向表中添加数据
        if(table != null)
            table.put(put);
        table.close();
    }

	
	/*
	插入一些数据,为后续实验做数据准备
	*/
    @Test
    public void insertBatchData() throws IOException {

        //获取连接
        Configuration configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.quorum", "node01:2181,node02:2181");
        Connection connection = ConnectionFactory.createConnection(configuration);
        //获取表
        Table myuser = connection.getTable(TableName.valueOf("myuser"));
        //创建put对象,并指定rowkey
        Put put = new Put("0002".getBytes());
        put.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(1));
        put.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("曹操"));
        put.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(30));
        put.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("沛国谯县"));
        put.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("16888888888"));
        put.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("helloworld"));

        Put put2 = new Put("0003".getBytes());
        put2.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(2));
        put2.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("刘备"));
        put2.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(32));
        put2.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put2.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("幽州涿郡涿县"));
        put2.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("17888888888"));
        put2.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("talk is cheap , show me the code"));


        Put put3 = new Put("0004".getBytes());
        put3.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(3));
        put3.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("孙权"));
        put3.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(35));
        put3.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put3.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("下邳"));
        put3.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("12888888888"));
        put3.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("what are you 弄啥嘞!"));

        Put put4 = new Put("0005".getBytes());
        put4.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(4));
        put4.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("诸葛亮"));
        put4.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(28));
        put4.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put4.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("四川隆中"));
        put4.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("14888888888"));
        put4.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("出师表你背了嘛"));

        Put put5 = new Put("0006".getBytes());
        put5.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(5));
        put5.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("司马懿"));
        put5.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(27));
        put5.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put5.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("哪里人有待考究"));
        put5.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("15888888888"));
        put5.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("跟诸葛亮死掐"));


        Put put6 = new Put("0007".getBytes());
        put6.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(5));
        put6.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("xiaobubu—吕布"));
        put6.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(28));
        put6.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put6.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("内蒙人"));
        put6.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("15788888888"));
        put6.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("貂蝉去哪了"));

        List<Put> listPut = new ArrayList<Put>();
        listPut.add(put);
        listPut.add(put2);
        listPut.add(put3);
        listPut.add(put4);
        listPut.add(put5);
        listPut.add(put6);

        myuser.put(listPut);
        myuser.close();
    }

    /**
     * 查询rowkey为0003的人
     */
    @Test
    public void getDataByRowKey() throws IOException {
        //获取连接
        //获取对应的表

        Get get = new Get(Bytes.toBytes("0003"));

        //通过get来获取数据  result里面封装了我们的结果数据
        Result result = table.get(get);

        //打印结果数据.获取这条数据所有的cell
        List<Cell> cells = result.listCells();
        for (Cell cell : cells) {
            //获取列族名
            byte[] family = cell.getFamily();
            //获取列名
            byte[] qualifier = cell.getQualifier();
            //获取列值
            byte[] value = cell.getValue();
            String s1 = new String(family);

            java.lang.String familyName = Bytes.toString(family);
            //判断,如果是id列和age列,转换成为int类型输出
            if("f1".equals(familyName) &&  "id".equals(Bytes.toString(qualifier)) || "age".equals(Bytes.toString(qualifier))){
                System.out.println("列族名称为"+ familyName + "列名称为" + Bytes.toString(qualifier)  +"列值为====" + Bytes.toInt(value) );
            }else{
                System.out.println("列族名称为"+ familyName + "列名称为" + Bytes.toString(qualifier)  +"列值为====" +  Bytes.toString(value) );
            }
        }
    }

    /**
     * 查询指定列族下面指定列的值
     *
     */
    @Test
    public  void  getColumn() throws IOException {
        Get get = new Get("0003".getBytes());
        get.addColumn("f1".getBytes(), "name".getBytes());
        get.addColumn("f2".getBytes(),"phone".getBytes());
        Result result = table.get(get);
        List<Cell> cells = result.listCells();
        for (Cell cell : cells) {
            //获取列族
            byte[] family = cell.getFamily();
            //获取列名
            byte[] qualifier = cell.getQualifier();
            //获取列值
            byte[] value = cell.getValue();
            System.out.println(Bytes.toString(value));


        }


    }

    /**
     * 查询指定列族下面的所有列
     *
     */
    @Test
    public  void  getFamily() throws IOException {
        Get get = new Get("0003".getBytes());
        get.addFamily("f2".getBytes());
        Result result = table.get(get);
        List<Cell> cells = result.listCells();
        for (Cell cell : cells) {
            //获取列族
            byte[] family = cell.getFamily();
            //获取列名
            byte[] qualifier = cell.getQualifier();
            //获取列值
            byte[] value = cell.getValue();
            System.out.println(Bytes.toString(value));


        }
    }


    /**
     * 通过rowkey的范围值进行扫描
     * 扫描  0004   到0006的所有的数据
     */
    @Test
    public  void  rangeRowkey() throws IOException {
        Scan scan = new Scan();
        //不设置StartRow和StopRow就是scan整个表
        scan.setStartRow("0004".getBytes());
        scan.setStopRow("0006".getBytes());

        //ResultScanner 里面封装了我们多条数据
        ResultScanner scanner = table.getScanner(scan);
        //循环遍历ResultScanner 得到一个个的Result
        for (Result result : scanner) {
            //获取数据的rowkey
            byte[] row = result.getRow();
            System.out.println("数据的rowkey为" +  Bytes.toString(row));


            List<Cell> cells = result.listCells();
            for (Cell cell : cells) {
                byte[] family = cell.getFamily();
                String familyName = Bytes.toString(family);
                byte[] qualifier = cell.getQualifier();
                byte[] value = cell.getValue();
                //判断,如果是id列和age列,转换成为int类型输出
                if("f1".equals(familyName) &&  "id".equals(Bytes.toString(qualifier)) || "age".equals(Bytes.toString(qualifier))){
                    System.out.println("列族名称为"+ familyName + "列名称为" + Bytes.toString(qualifier)  +"列值为====" + Bytes.toInt(value) );
                }else{
                    System.out.println("列族名称为"+ familyName + "列名称为" + Bytes.toString(qualifier)  +"列值为====" +  Bytes.toString(value) );
                }

            }


        }
    }

    /**
     * 过滤rowkey比0003还要小的数据
     */
    @Test
    public   void  rowFilterStudy() throws IOException {
        Scan scan = new Scan();
        //通过rowFilter实现数据按照rowkey进行过滤
        BinaryComparator binaryComparator = new BinaryComparator("0003".getBytes());

        RowFilter rowFilter = new RowFilter(CompareFilter.CompareOp.LESS, binaryComparator);
        scan.setFilter(rowFilter);
        ResultScanner scanner = table.getScanner(scan);
        for (Result result : scanner) {
            byte[] row = result.getRow();
            System.out.println("数据的rowkey为" +  Bytes.toString(row));

            List<Cell> cells = result.listCells();
            for (Cell cell : cells) {
                byte[] family = cell.getFamily();
                byte[] qualifier = cell.getQualifier();
                byte[] value = cell.getValue();

                //id列和age列是整型的数据
                if("f1".equals(Bytes.toString(family)) && "id".equals(Bytes.toString(qualifier))  || "age".equals(Bytes.toString(qualifier)) ){
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toInt(value));
                }else{
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toString(value));
                }
            }
        }


    }

    /**
     * 列族过滤器,只需要获取f2列族下面的列
     */
    @Test
    public void familyFilter() throws IOException {
        Scan scan = new Scan();
        SubstringComparator substringComparator = new SubstringComparator("f2");

        FamilyFilter familyFilter = new FamilyFilter(CompareFilter.CompareOp.EQUAL, substringComparator);

        scan.setFilter(familyFilter);


        ResultScanner scanner = table.getScanner(scan);
        for (Result result : scanner) {
            byte[] row = result.getRow();
            System.out.println("数据的rowkey为" +  Bytes.toString(row));

            List<Cell> cells = result.listCells();
            for (Cell cell : cells) {
                byte[] family = cell.getFamily();
                byte[] qualifier = cell.getQualifier();
                byte[] value = cell.getValue();

                //id列和age列是整型的数据
                if("f1".equals(Bytes.toString(family)) && "id".equals(Bytes.toString(qualifier))  || "age".equals(Bytes.toString(qualifier)) ){
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toInt(value));
                }else{
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toString(value));
                }
            }
        }
    }

    /**
     * 列名过滤器,只查询,列名为name的这一列数据
     */
    @Test
    public  void  qualifierFilter() throws IOException {

        Scan scan = new Scan();

        QualifierFilter qualifierFilter = new QualifierFilter(CompareFilter.CompareOp.EQUAL, new SubstringComparator("name"));


        scan.setFilter(qualifierFilter);


        ResultScanner scanner = table.getScanner(scan);

        for (Result result : scanner) {
            byte[] row = result.getRow();
            System.out.println("数据的rowkey为" +  Bytes.toString(row));

            List<Cell> cells = result.listCells();
            for (Cell cell : cells) {
                byte[] family = cell.getFamily();
                byte[] qualifier = cell.getQualifier();
                byte[] value = cell.getValue();

                //id列和age列是整型的数据
                if("f1".equals(Bytes.toString(family)) && "id".equals(Bytes.toString(qualifier))  || "age".equals(Bytes.toString(qualifier)) ){
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toInt(value));
                }else{
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toString(value));
                }
            }
        }
    }

    /**
     * 查修列值当中包含8的列,返回回来
     */
    @Test
    public void valueFilter() throws IOException {
        Scan scan = new Scan();
        ValueFilter valueFilter = new ValueFilter(CompareFilter.CompareOp.EQUAL, new SubstringComparator("8"));

        scan.setFilter(valueFilter);


        ResultScanner scanner = table.getScanner(scan);
        for (Result result : scanner) {
            byte[] row = result.getRow();
            System.out.println("数据的rowkey为" +  Bytes.toString(row));

            List<Cell> cells = result.listCells();
            for (Cell cell : cells) {
                byte[] family = cell.getFamily();
                byte[] qualifier = cell.getQualifier();
                byte[] value = cell.getValue();

                //id列和age列是整型的数据
                if("f1".equals(Bytes.toString(family)) && "id".equals(Bytes.toString(qualifier))  || "age".equals(Bytes.toString(qualifier)) ){
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toInt(value));
                }else{
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toString(value));
                }
            }
        }

    }


    /**
     * 查询name为刘备的人
     */
    @Test
    public void singleColumnValueFilter() throws IOException {

        Scan scan = new Scan();

        /**
         * @param family name of column family
         * @param qualifier name of column qualifier
         * @param compareOp operator
         * @param value value to compare column values against
         */
        SingleColumnValueFilter singleColumnValueFilter = new SingleColumnValueFilter("f1".getBytes(), "name".getBytes(), CompareFilter.CompareOp.EQUAL, "刘备".getBytes());

        scan.setFilter(singleColumnValueFilter);

        ResultScanner scanner = table.getScanner(scan);
        for (Result result : scanner) {
            byte[] row = result.getRow();
            System.out.println("数据的rowkey为" +  Bytes.toString(row));

            List<Cell> cells = result.listCells();
            for (Cell cell : cells) {
                byte[] family = cell.getFamily();
                byte[] qualifier = cell.getQualifier();
                byte[] value = cell.getValue();

                //id列和age列是整型的数据
                if("f1".equals(Bytes.toString(family)) && "id".equals(Bytes.toString(qualifier))  || "age".equals(Bytes.toString(qualifier)) ){
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toInt(value));
                }else{
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toString(value));
                }
            }
        }

    }


    /**
     * 查询rowkey以00开头所有的数据  PrefixFilter
     */
    @Test
    public  void  prefixFilter() throws IOException {


        Scan scan = new Scan();

        PrefixFilter prefixFilter = new PrefixFilter("00".getBytes());

        scan.setFilter(prefixFilter);

        ResultScanner scanner = table.getScanner(scan);


        for (Result result : scanner) {
            byte[] row = result.getRow();
            System.out.println("数据的rowkey为" +  Bytes.toString(row));

            List<Cell> cells = result.listCells();
            for (Cell cell : cells) {
                byte[] family = cell.getFamily();
                byte[] qualifier = cell.getQualifier();
                byte[] value = cell.getValue();

                //id列和age列是整型的数据
                if("f1".equals(Bytes.toString(family)) && "id".equals(Bytes.toString(qualifier))  || "age".equals(Bytes.toString(qualifier)) ){
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toInt(value));
                }else{
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toString(value));
                }
            }
        }
    }

    /**
     * hbase当中分页
     * 分页两个条件
     * pageNum
     * pageSize
     */
    @Test
    public  void  pageFilter() throws IOException {

        int pageNum =3 ;
        int pageSize = 2;

        if(pageNum  == 1 ){
            Scan scan = new Scan();
            scan.setStartRow("".getBytes());   //设置我们的起始rowkey
            scan.setMaxResultSize(pageSize);  //设置最大的返回结果返回两条
            PageFilter filter = new PageFilter(pageSize);
            scan.setFilter(filter);

            ResultScanner scanner = table.getScanner(scan);
            for (Result result : scanner) {
                byte[] row = result.getRow();
                System.out.println("数据的rowkey为" +  Bytes.toString(row));

                List<Cell> cells = result.listCells();
                for (Cell cell : cells) {
                    byte[] family = cell.getFamily();
                    byte[] qualifier = cell.getQualifier();
                    byte[] value = cell.getValue();

                    //id列和age列是整型的数据
                    if("f1".equals(Bytes.toString(family)) && "id".equals(Bytes.toString(qualifier))  || "age".equals(Bytes.toString(qualifier)) ){
                        System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toInt(value));
                    }else{
                        System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toString(value));
                    }
                }
            }
        }else{
            String  startRow = "";
            Scan scan = new Scan();
            int resultSize = (pageNum - 1) * pageSize + 1;
            scan.setMaxResultSize(resultSize);
            PageFilter filter = new PageFilter(resultSize);//设置我们一次性往前扫描5条,最后一个rowkey就是我们第三页的起始rowkey
            scan.setFilter(filter);
            ResultScanner scanner = table.getScanner(scan);  //resultScanner里面包含了5条
            for (Result result : scanner) {
                //获取我们rowkey
                byte[] row = result.getRow();
                startRow = Bytes.toString(row);  //最后一次循环遍历  rowkey为0005

            }
            //根据我们求取出来的startRow来实现我们第三页数据的查询
            Scan scan2 = new Scan();
            scan2.setStartRow(startRow.getBytes());
            scan2.setMaxResultSize(pageSize);

            PageFilter filter1 = new PageFilter(pageSize);
            scan2.setFilter(filter1);

            ResultScanner scanner1 = table.getScanner(scan2);
            for (Result result : scanner1) {
                byte[] row = result.getRow();
                System.out.println("数据的rowkey为" +  Bytes.toString(row));

                List<Cell> cells = result.listCells();
                for (Cell cell : cells) {
                    byte[] family = cell.getFamily();
                    byte[] qualifier = cell.getQualifier();
                    byte[] value = cell.getValue();

                    //id列和age列是整型的数据
                    if("f1".equals(Bytes.toString(family)) && "id".equals(Bytes.toString(qualifier))  || "age".equals(Bytes.toString(qualifier)) ){
                        System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toInt(value));
                    }else{
                        System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toString(value));
                    }
                }
            }
        }
        //分为两种条件进行判断,第一页和其他页
    }

    /**
     * 多过滤器综合查询
     * 需求:使用SingleColumnValueFilter查询f1列族,name为刘备的数据,并且同时满足rowkey的前缀以00开头的数据(PrefixFilter)
     */
    @Test
    public  void filterList() throws IOException {
        /**
         * final byte [] family, final byte [] qualifier,
         final CompareOp compareOp, final byte[] value
         */
        SingleColumnValueFilter singleColumnValueFilter = new SingleColumnValueFilter(
                "f1".getBytes(),
                "name".getBytes(),
                CompareFilter.CompareOp.EQUAL, "刘备".getBytes());

        PrefixFilter prefixFilter = new PrefixFilter("00".getBytes());

        FilterList filterList = new FilterList(singleColumnValueFilter, prefixFilter);


        Scan scan = new Scan();
        scan.setFilter(filterList);

        ResultScanner scanner = table.getScanner(scan);
        for (Result result : scanner) {
            byte[] row = result.getRow();
            System.out.println("数据的rowkey为" +  Bytes.toString(row));

            List<Cell> cells = result.listCells();
            for (Cell cell : cells) {
                byte[] family = cell.getFamily();
                byte[] qualifier = cell.getQualifier();
                byte[] value = cell.getValue();

                //id列和age列是整型的数据
                if("f1".equals(Bytes.toString(family)) && "id".equals(Bytes.toString(qualifier))  || "age".equals(Bytes.toString(qualifier)) ){
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toInt(value));
                }else{
                    System.out.println("列族为" +  Bytes.toString(family) + "列名为" +  Bytes.toString(qualifier) + "列值为" +  Bytes.toString(value));
                }
            }
        }
    }

    /**
     * 根据rowkey删除数据
     */
    @Test
    public void deleteData() throws IOException {

        Delete delete = new Delete("0007".getBytes());

        table.delete(delete);

    }


    /**
     * drop表操作
     */
    @Test
    public void  deleteTable() throws IOException {
        //获取连接
        Configuration configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.quorum","node01:2181,node02:2181,node03:2181");
        Connection connection = ConnectionFactory.createConnection(configuration);
        Admin admin = connection.getAdmin();
        admin.disableTable(TableName.valueOf("myuser"));
        admin.deleteTable(TableName.valueOf("myuser"));
        admin.close();
    }

    @AfterTest
    public void closeConnection() throws IOException
    {
        connection.close();
    }
}

HBase底层原理

系统架构

在这里插入图片描述
Client

  1. 包含访问hbase的接口,client维护着一些cache来加快对hbase的访问,比如regione的位置信息。
    Zookeeper
  2. 保证任何时候,集群中只有一个master
  3. 存贮所有Region的寻址入口----root表在哪台服务器上。
  4. 实时监控Region Server的状态,将Region server的上线和下线信息实时通知给Master
  5. 存储Hbase的schema,包括有哪些table,每个table有哪些column family
    Master职责
  6. 为Region server分配region
  7. 负责region server的负载均衡
  8. 发现失效的region server并重新分配其上的region
  9. HDFS上的垃圾文件回收
  10. 处理schema更新请求
    Region Server职责
  11. Region server维护Master分配给它的region,处理对这些region的IO请求
  12. Region server负责切分在运行过程中变得过大的region
    可以看到,client访问hbase上数据的过程并不需要master参与(寻址访问zookeeper和region server,数据读写访问regione server),master仅仅维护者table和region的元数据信息,负载很低。

HBase的表数据模型在这里插入图片描述

Row Key

与nosql数据库们一样,row key是用来检索记录的主键。访问hbase table中的行,只有三种方式:

  1. 通过单个row key访问
  2. 通过row key的range
  3. 全表扫描
    Row key行键 (Row key)可以是任意字符串(最大长度是 64KB,实际应用中长度一般为 10-100bytes),在hbase内部,row key保存为字节数组。
    Hbase会对表中的数据按照rowkey排序(字典顺序)

存储时,数据按照Row key的字典序(byte order)排序存储。设计key时,要充分排序存储这个特性,将经常一起读取的行存储放到一起。(位置相关性)
注意:
字典序对int排序的结果是
1,10,100,11,12,13,14,15,16,17,18,19,2,20,21,…,9,91,92,93,94,95,96,97,98,99。要保持整形的自然序,行键必须用0作左填充。
行的一次读写是原子操作 (不论一次读写多少列)。这个设计决策能够使用户很容易的理解程序在对同一个行进行并发更新操作时的行为。

列族Column Family

hbase表中的每个列,都归属与某个列族。列族是表的schema的一部分(而列不是),必须在使用表之前定义。
列名都以列族作为前缀。例如courses:history , courses:math 都属于 courses 这个列族。
访问控制、磁盘和内存的使用统计都是在列族层面进行的。
列族越多,在取一行数据时所要参与IO、搜寻的文件就越多,所以,如果没有必要,不要设置太多的列族

列 Column

列族下面的具体列,属于某一个ColumnFamily,类似于我们mysql当中创建的具体的列

时间戳

HBase中通过row和columns确定的为一个存贮单元称为cell。每个 cell都保存着同一份数据的多个版本。版本通过时间戳来索引。时间戳的类型是 64位整型。时间戳可以由hbase(在数据写入时自动 )赋值,此时时间戳是精确到毫秒的当前系统时间。时间戳也可以由客户显式赋值。如果应用程序要避免数据版本冲突,就必须自己生成具有唯一性的时间戳。每个 cell中,不同版本的数据按照时间倒序排序,即最新的数据排在最前面。

为了避免数据存在过多版本造成的的管理 (包括存贮和索引)负担,hbase提供了两种数据版本回收方式:

  • 保存数据的最后n个版本
  • 保存最近一段时间内的版本(设置数据的生命周期TTL)。
    用户可以针对每个列族进行设置。

Cell

由{row key, column( = +

VersionNum

数据的版本号,每条数据可以有多个版本号,默认值为系统时间戳,类型为Long

物理存储

1、整体结构

在这里插入图片描述
1 Table中的所有行都按照row key的字典序排列。
2 Table 在行的方向上分割为多个Hregion。

3 region按大小分割的(默认10G),每个表一开始只有一个region,随着数据不断插入表,region不断增大,当增大到一个阀值的时候,Hregion就会等分会两个新的Hregion。当table中的行不断增多,就会有越来越多的Hregion。

4 Hregion是Hbase中分布式存储和负载均衡的最小单元。最小单元就表示不同的Hregion可以分布在不同的HRegion server上。但一个Hregion是不会拆分到多个server上的。

5 HRegion虽然是负载均衡的最小单元,但并不是物理存储的最小单元。
事实上,HRegion由一个或者多个Store组成,每个store保存一个column family。
每个Strore又由一个memStore和0至多个StoreFile组成。如上图

2、STORE FILE & HFILE结构

StoreFile以HFile格式保存在HDFS上。
附:HFile的格式为:
在这里插入图片描述
首先HFile文件是不定长的,长度固定的只有其中的两块:Trailer和FileInfo。正如图中所示的,Trailer中有指针指向其他数 据块的起始点。
File Info中记录了文件的一些Meta信息,例如:AVG_KEY_LEN, AVG_VALUE_LEN, LAST_KEY, COMPARATOR, MAX_SEQ_ID_KEY等。
Data Index和Meta Index块记录了每个Data块和Meta块的起始点。
Data Block是HBase I/O的基本单元,为了提高效率,HRegionServer中有基于LRU的Block Cache机制。每个Data块的大小可以在创建一个Table的时候通过参数指定,大号的Block有利于顺序Scan,小号Block利于随机查询。 每个Data块除了开头的Magic以外就是一个个KeyValue对拼接而成, Magic内容就是一些随机数字,目的是防止数据损坏。
HFile里面的每个KeyValue对就是一个简单的byte数组。但是这个byte数组里面包含了很多项,并且有固定的结构。我们来看看里面的具体结构:
在这里插入图片描述
开始是两个固定长度的数值,分别表示Key的长度和Value的长度。紧接着是Key,开始是固定长度的数值,表示RowKey的长度,紧接着是 RowKey,然后是固定长度的数值,表示Family的长度,然后是Family,接着是Qualifier,然后是两个固定长度的数值,表示Time Stamp和Key Type(Put/Delete)。Value部分没有这么复杂的结构,就是纯粹的二进制数据了。

HFile分为六个部分:
Data Block 段–保存表中的数据,这部分可以被压缩
Meta Block 段 (可选的)–保存用户自定义的kv对,可以被压缩。
File Info 段–Hfile的元信息,不被压缩,用户也可以在这一部分添加自己的元信息。
Data Block Index 段–Data Block的索引。每条索引的key是被索引的block的第一条记录的key。
Meta Block Index段 (可选的)–Meta Block的索引。
Trailer–这一段是定长的。保存了每一段的偏移量,读取一个HFile时,会首先 读取Trailer,Trailer保存了每个段的起始位置(段的Magic Number用来做安全check),然后,DataBlock Index会被读取到内存中,这样,当检索某个key时,不需要扫描整个HFile,而只需从内存中找到key所在的block,通过一次磁盘io将整个 block读取到内存中,再找到需要的key。DataBlock Index采用LRU机制淘汰。
HFile的Data Block,Meta Block通常采用压缩方式存储,压缩之后可以大大减少网络IO和磁盘IO,随之而来的开销当然是需要花费cpu进行压缩和解压缩。
目标Hfile的压缩支持两种方式:Gzip,Lzo。

3、Memstore与storefile

一个region由多个store组成,每个store包含一个列族的所有数据
Store包括位于内存的memstore和位于硬盘的storefile
写操作先写入memstore,当memstore中的数据量达到某个阈值,Hregionserver启动flashcache进程写入storefile,每次写入形成单独一个storefile
当storefile大小超过一定阈值后,会把当前的region分割成两个,并由Hmaster分配给相应的region服务器,实现负载均衡
客户端检索数据时,先在memstore找,找不到再找storefile

4、HLog(WAL log)

WAL 意为Write ahead log(http://en.wikipedia.org/wiki/Write-ahead_logging),类似mysql中的binlog,用来 做灾难恢复时用,Hlog记录数据的所有变更,一旦数据修改,就可以从log中进行恢复。
每个Region Server维护一个Hlog,而不是每个Region一个。这样不同region(来自不同table)的日志会混在一起,这样做的目的是不断追加单个文件相对于同时写多个文件而言,可以减少磁盘寻址次数,因此可以提高对table的写性能。带来的麻烦是,如果一台region server下线,为了恢复其上的region,需要将region server上的log进行拆分,然后分发到其它region server上进行恢复。
HLog文件就是一个普通的Hadoop Sequence File:

  • HLog Sequence File 的Key是HLogKey对象,HLogKey中记录了写入数据的归属信息,除了table和region名字外,同时还包括 sequence number和timestamp,timestamp是”写入时间”,sequence number的起始值为0,或者是最近一次存入文件系统中sequence number。
  • HLog Sequece File的Value是HBase的KeyValue对象,即对应HFile中的KeyValue,可参见上文描述。

读写过程

1、读请求过程:

HRegionServer保存着meta表以及表数据,要访问表数据,首先Client先去访问zookeeper,从zookeeper里面获取meta表所在的位置信息,即找到这个meta表在哪个HRegionServer上保存着。

接着Client通过刚才获取到的HRegionServer的IP来访问Meta表所在的HRegionServer,从而读取到Meta,进而获取到Meta表中存放的元数据。

Client通过元数据中存储的信息,访问对应的HRegionServer,然后扫描所在HRegionServer的Memstore和Storefile来查询数据。

最后HRegionServer把查询到的数据响应给Client。

2、写请求过程:

Client也是先访问zookeeper,找到Meta表,并获取Meta表元数据。

确定当前将要写入的数据所对应的HRegion和HRegionServer服务器。

Client向该HRegionServer服务器发起写入数据请求,然后HRegionServer收到请求并响应。

Client先把数据写入到HLog,以防止数据丢失。

然后将数据写入到Memstore。

如果HLog和Memstore均写入成功,则这条数据写入成功

如果Memstore达到阈值,会把Memstore中的数据flush到Storefile中。

当Storefile越来越多,会触发Compact合并操作,把过多的Storefile合并成一个大的Storefile。

当Storefile越来越大,Region也会越来越大,达到阈值后,会触发Split操作,将Region一分为二。

细节描述:
hbase使用MemStore和StoreFile存储对表的更新。
数据在更新时首先写入Log(WAL log)和内存(MemStore)中,MemStore中的数据是排序的,当MemStore累计到一定阈值时,就会创建一个新的MemStore,并 且将老的MemStore添加到flush队列,由单独的线程flush到磁盘上,成为一个StoreFile。于此同时,系统会在zookeeper中记录一个redo point,表示这个时刻之前的变更已经持久化了。
当系统出现意外时,可能导致内存(MemStore)中的数据丢失,此时使用Log(WAL log)来恢复checkpoint之后的数据。

StoreFile是只读的,一旦创建后就不可以再修改。因此Hbase的更新其实是不断追加的操作。当一个Store中的StoreFile达到一定的阈值后,就会进行一次合并(minor_compact, major_compact),将对同一个key的修改合并到一起,形成一个大的StoreFile,当StoreFile的大小达到一定阈值后,又会对 StoreFile进行split,等分为两个StoreFile。
由于对表的更新是不断追加的,compact时,需要访问Store中全部的 StoreFile和MemStore,将他们按row key进行合并,由于StoreFile和MemStore都是经过排序的,并且StoreFile带有内存中索引,合并的过程还是比较快。

Region管理

(1) region分配
任何时刻,一个region只能分配给一个region server。master记录了当前有哪些可用的region server。以及当前哪些region分配给了哪些region server,哪些region还没有分配。当需要分配的新的region,并且有一个region server上有可用空间时,master就给这个region server发送一个装载请求,把region分配给这个region server。region server得到请求后,就开始对此region提供服务。

(2) region server上线
master使用zookeeper来跟踪region server状态。当某个region server启动时,会首先在zookeeper上的server目录下建立代表自己的znode。由于master订阅了server目录上的变更消息,当server目录下的文件出现新增或删除操作时,master可以得到来自zookeeper的实时通知。因此一旦region server上线,master能马上得到消息。

(3) region server下线
当region server下线时,它和zookeeper的会话断开,zookeeper而自动释放代表这台server的文件上的独占锁。master就可以确定:
1 region server和zookeeper之间的网络断开了。
2 region server挂了。
无论哪种情况,region server都无法继续为它的region提供服务了,此时master会删除server目录下代表这台region server的znode数据,并将这台region server的region分配给其它还活着的同志。

Master工作机制

master上线

master启动进行以下步骤:
1 从zookeeper上获取唯一一个代表active master的锁,用来阻止其它master成为master。
2 扫描zookeeper上的server父节点,获得当前可用的region server列表。
3 和每个region server通信,获得当前已分配的region和region server的对应关系。
4 扫描.META.region的集合,计算得到当前还未分配的region,将他们放入待分配region列表。

master下线

由于master只维护表和region的元数据,而不参与表数据IO的过程,master下线仅导致所有元数据的修改被冻结(无法创建删除表,无法修改表的schema,无法进行region的负载均衡,无法处理region 上下线,无法进行region的合并,唯一例外的是region的split可以正常进行,因为只有region server参与),表的数据读写还可以正常进行。因此master下线短时间内对整个hbase集群没有影响。
从上线过程可以看到,master保存的信息全是可以冗余信息(都可以从系统其它地方收集到或者计算出来)
因此,一般hbase集群中总是有一个master在提供服务,还有一个以上的‘master’在等待时机抢占它的位置。

HBase的三个重要机制

1、flush机制

当MemStore达到阈值,将Memstore中的数据Flush进Storefile
涉及属性:
hbase.hregion.memstore.flush.size:134217728
即:128M就是Memstore的默认阈值

hbase.regionserver.global.memstore.upperLimit:0.4
即:这个参数的作用是当单个HRegion内所有的Memstore大小总和超过指定值时,flush该HRegion的所有memstore。RegionServer的flush是通过将请求添加一个队列,模拟生产消费模式来异步处理的。那这里就有一个问题,当队列来不及消费,产生大量积压请求时,可能会导致内存陡增,最坏的情况是触发OOM。

hbase.regionserver.global.memstore.lowerLimit:0.38
即:当MemStore使用内存总量达到hbase.regionserver.global.memstore.upperLimit指定值时,将会有多个MemStores flush到文件中,MemStore flush 顺序是按照大小降序执行的,直到刷新到MemStore使用内存略小于lowerLimit

2、 compact机制

http://archive.cloudera.com/cdh5/cdh/5/hbase-1.2.0-cdh5.14.0/book.html#compaction

把小的Memstore文件合并成大的Storefile文件。

3、split机制

当Region达到阈值,会把过大的Region一分为二。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值