java: 从HBase中读取数据

一、添加依赖:

        
            org.apache.hadoop
            hadoop-client
            2.6.0
        

        
            org.apache.hbase
            hbase-client
            2.4.2
        


二、使用Scanner读取数据示例:

package cn.edu.tju;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellScanner;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;

public class TestHBaseRead {
    public static void main(String[] args) throws Exception {
        Configuration config = HBaseConfiguration.create();// create configuration
        //zookeeper 地址
        config.set("hbase.zookeeper.quorum","xxx.xxx.xxx.xxx");//
        //zookeeper端口
        config.set("hbase.zookeeper.property.clientPort", "2181");//
        //表名,必须提前在hbase中创建
        String tableName ="c1";
        //row key
        String rowKey = "myKey2";
        //family,必须是hbase中有的family
        String familyName = "fm2";
        //指定的某个column name
        String specifiedColumnName = "by";

        Connection connection = ConnectionFactory.createConnection(config);

        Get g = new Get(rowKey.getBytes());
        g.addFamily(familyName.getBytes());
        try {
            Table table = connection.getTable(TableName.valueOf(tableName));
            Result result = table.get(g);
            CellScanner cellScanner =result.cellScanner();
            while (cellScanner.advance()){
                Cell cell = cellScanner.current();
                byte[] rowArray = cell.getRowArray(); //row key 字节数组
                byte[] familyArray = cell.getFamilyArray(); //列族 字节数组
                byte[] qualifierArray = cell.getQualifierArray();//列名 字节数据
                byte[] valueArray = cell.getValueArray();// 值 字节数组

                String columnName=new String(qualifierArray,cell.getQualifierOffset(),cell.getQualifierLength());
                String columnValue=new String(valueArray,cell.getValueOffset(),cell.getValueLength());
                if(specifiedColumnName.equals(columnName)){
                    System.out.println(columnValue);
                }
            }
        }catch(Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

你可能感兴趣的:(Hadoop,java)