HBase API 的用法总结

一、获得connection

因为connection为重量级框架,而admin 和table 为轻量级框架,所以在进行操作前,需要先初始化一个connection

public class ConnectionUtil {

    //可以获取Connection对象的方法
    public  static Connection getConn() throws IOException {

        return ConnectionFactory.createConnection();

    }

    //关闭connection对象的方法
    public static void  close(Connection conn) throws IOException {

        if (conn !=null){

            conn.close();

        }

    }


}

二、针对NameSpace 的API

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * Created by VULCAN on 2020/3/20
 */
public class NameSpaceUtil {

    private  static Logger logger= LoggerFactory.getLogger(NameSpaceUtil.class);

    //list_namespace 查询所有库
    public  static List<String> listNameSpaces(Connection conn) throws IOException {

        ArrayList<String> nameSpaces = new ArrayList<>();

        //获取一个Admin对象
        Admin admin = conn.getAdmin();

        //调用方法取得带有namespace信息的descriptor
        NamespaceDescriptor[] namespaceDescriptors = admin.listNamespaceDescriptors();

        for (NamespaceDescriptor namespaceDescriptor : namespaceDescriptors) {

            nameSpaces.add(namespaceDescriptor.getName());

        }

        //关闭admin
        admin.close();

        return nameSpaces;

    }

    //判断库是否存在
    public  static  boolean  ifNSExists(Connection conn,String nsName) throws IOException {

        //校验库名,当字符串为null或者空字符时,返回true
        if (StringUtils.isBlank(nsName)){

            logger.error("请输入正确的库名!");

            return false;
        }

        //获取一个Admin对象
        Admin admin = conn.getAdmin();

        try {
            //根据库名获取库的描述,如果库的描述不存在,抛出NamespaceNotFoundException
            admin.getNamespaceDescriptor(nsName);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return  false;
        } finally {
            admin.close();
        }

    }


    // 创建库
    public  static  boolean  createNameSpace(Connection conn,String nsName) throws IOException {

        //校验库名
        if (StringUtils.isBlank(nsName)){

            logger.error("请输入正确的库名!");

            return false;
        }

        //获取一个Admin对象
        Admin admin = conn.getAdmin();

        try {
            //创建库的描述
                //此处只能用内部类bulid来创建descriptor对象
            NamespaceDescriptor namespaceDescriptor = NamespaceDescriptor.create(nsName).build();

            //根据库的描述创建库
            admin.createNamespace(namespaceDescriptor);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;

        } finally {
            admin.close();
        }

    }

    // 删除库 只能删除空库,库中有表无法删除
    public  static  boolean dropNameSpace(Connection conn,String nsName) throws IOException {

        //判断库是否存在,不存在就不需要删除
        if (!ifNSExists(conn,nsName)){

            logger.error("当前库:"+nsName+",不存在!");

            return false;

        }

        //判断库是否是空库
        List<String> tablesInNameSpace = getTablesInNameSpace(conn, nsName);

        if (!tablesInNameSpace.isEmpty()){

            logger.error("当前库:"+nsName+",非空!");

            return false;

        }

        //获取一个Admin对象
        Admin admin = conn.getAdmin();

        try {
            //删库
            admin.deleteNamespace(nsName);

            return true;
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        } finally {

            admin.close();

        }

    }

    //获取库中所有的表
    public static  List<String> getTablesInNameSpace(Connection conn,String nsName) throws IOException {

        ArrayList<String> tableNames = new ArrayList<>();

        //获取一个Admin对象
        Admin admin = conn.getAdmin();

        TableName[] tableNames1 = admin.listTableNamesByNamespace(nsName);
        for (TableName tableName : tableNames1) {
            tableNames.add(tableName.toString());
        }

        //关闭admin
        admin.close();

        return tableNames;


    }

}

三、针对表的操作

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by VULCAN on 2020/3/20
 */
public class TableUtil {

    private  static Logger logger= LoggerFactory.getLogger(TableUtil.class);


    //判断表名是否合法,如果合法返回表的TableName,如果不合法,返回null
    public static TableName checkTableName(String tableName, String nsname){

        //验证表名是否合法
        if (StringUtils.isBlank(tableName)){

            logger.error("请输入正确的表名!");

            return null;

        }

        return  TableName.valueOf(nsname,tableName);

    }

    //判断表是否存在
    public static boolean ifTableExists(Connection connection, String tableName, String nsname) throws IOException {

        //验证表名是否合法
        TableName tn = checkTableName(tableName, nsname);

        if (tn==null){

            return false;
        }

        Admin admin = connection.getAdmin();

        boolean tableExists = admin.tableExists(tn);

        admin.close();

        return tableExists;

    }

    //创建表
    public static boolean createTable(Connection connection, String tableName, String nsname,String...cfs) throws IOException {

        //验证表是否存在
        if(ifTableExists(connection,tableName, nsname)){

            logger.warn(tableName+"已经存在!无需再创建!");

            return false;

        };

        TableName tn = checkTableName(tableName, nsname);

        if (cfs.length<1){

            logger.warn("至少需要指定一个列族!");

            return false;

        }

        Admin admin = connection.getAdmin();

        //创建表的描述和定义
        HTableDescriptor hTableDescriptor = new HTableDescriptor(tn);

        //列族需要在表的描述和定义中指定

        for (String cf : cfs) {

            //定义列族
            HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(cf);

            //可以调用列族的set()方法设置列族的属性
           // hColumnDescriptor.setVersions()

            hTableDescriptor.addFamily(hColumnDescriptor);

        }
        //基于表的描述创建表
        admin.createTable(hTableDescriptor);

        admin.close();

        return true;

    }


    //删除表
    public static boolean dropTable(Connection connection, String tableName, String nsname) throws IOException {

        //验证表是否存在
        if(!ifTableExists(connection,tableName, nsname)){

            logger.warn(tableName+"不存在!无法删除!");

            return false;

        };

        //获取表名
        TableName tn = checkTableName(tableName, nsname);

        Admin admin = connection.getAdmin();

        //删除前,需要先disable表
        admin.disableTable(tn);

        //删除表
        admin.deleteTable(tn);

        admin.close();

        return true;

    }

}

 四、针对数据的操作

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * Created by VULCAN on 2020/3/21
 */
public class DataUtil {

    //返回指定表名的Table对象
    public static Table getTableByName(Connection conn,String nsName,String tableName) throws IOException {

        TableName tn = TableUtil.checkTableName(tableName, nsName);

        if (tn == null){

            return null;

        }

       return conn.getTable(tn);

    }

    //put    put 表名  rowkey 列族名:列名  值  [时间戳]  put是向某一行的某列添加一个value
    public static void put(Connection conn,String nsName,String tableName,String rowkey,String cfName,String cqName,String value) throws IOException {

        Table table = getTableByName(conn, nsName, tableName);

        if (table==null){
            return ;
        }

        //使用Table进行put操作
        // put对象需要基于rowkey构建
        Put put = new Put(Bytes.toBytes(rowkey));

        //向put对象中封装参数
        put.addColumn(Bytes.toBytes(cfName),Bytes.toBytes(cqName),Bytes.toBytes(value));
               // .addColumn().addColumn()

        table.put(put);

        table.close();

    }

    //get  查询一行的内容  get 表名 rowkey [列名]
    public  static  Result get(Connection conn,String nsName,String tableName,String rowkey) throws IOException {
        
        //获取表对象
        Table table = getTableByName(conn, nsName, tableName);

        if (table==null){
            return null;
        }
        
        //构建get对象
        Get get = new Get(Bytes.toBytes(rowkey));
        
        //向get中,封装查询的参数
        //只查询某个列
       // get.addColumn()
        // 只查某个列族
        //get.addFamily()
        //只查某个版本
        //get.setTimeStamp()
        //设置查询的最大版本数量
        ///get.setMaxVersions()

        Result result = table.get(get);

        table.close();

        return result;

    }

    //遍历单行Result中的数据
    public static  void  parseResult(Result result){

        if (result !=null){

            //遍历这一行内容所有的Cell
            Cell[] cells = result.rawCells();

            for (Cell cell : cells) {
                //利用Cell Util的clonexxx来获取相应的值

                System.out.println("Row:"+ Bytes.toString(CellUtil.cloneRow(cell)));
                System.out.println("Family:"+ Bytes.toString(CellUtil.cloneFamily(cell)));
                System.out.println("Qualifier:"+ Bytes.toString(CellUtil.cloneQualifier(cell)));
                System.out.println("Value:"+ Bytes.toString(CellUtil.cloneValue(cell)));

                System.out.println("-----------------------------------------");

            }

        }

    }

    //scan
    public static void  scan(Connection conn,String nsName,String tableName) throws IOException {

        //获取表对象
        Table table = getTableByName(conn, nsName, tableName);

        if (table==null){
            return ;
        }

        //scan代表一个扫描器
        Scan scan = new Scan();
        
        //在scan中设置要扫描的参数
        //只扫某些列
        //scan.addColumn()
        //只扫某个列族
        //scan.addFamily()
        // 指定起始行和终止行
        //scan.setStartRow()
        //scan.setStopRow()
        // 专家设置 ,{RAW=>TRUE,VERSIONS=>10}
        // scan.setMaxVersions(10);
        // scan.setRaw(true);

        ResultScanner scanner = table.getScanner(scan);

        for (Result result : scanner) {

            parseResult(result);

        }

        table.close();

    }

    //delete  delete 表名 rowkey [列名] [ts]
    public  static  void delete(Connection conn, String nsName, String tableName, String rowkey) throws IOException {

        //获取表对象
        Table table = getTableByName(conn, nsName, tableName);

        if (table==null){
            return ;
        }

        //删除一整行  为当前行的每个列族都添加一条  列族名:  ,type=DeleteFamily的记录
        Delete delete = new Delete(Bytes.toBytes(rowkey));

        //删除某个列族  为当前行的指定列族都添加一条  列族名:  ,type=DeleteFamily的记录
       // delete.addFamily(Bytes.toBytes("cf1"));

        // 删除某个列  为指定列添加一条 列族名:列名,type=Delete的记录  删除当前列最新版本的cell,如果
        // 有历史版本,历史版本是可见的
       // delete.addColumn(Bytes.toBytes("cf1"),Bytes.toBytes("name"));

        //删除指定列的所有版本  为指定的列添加一条 列族名:列名, type=DeleteColumn的记录
        delete.addColumns(Bytes.toBytes("cf1"),Bytes.toBytes("name"));

        table.delete(delete);

        table.close();

    }
}

 

posted @ 2020-03-20 20:38  可以看看你胖次吗  阅读(483)  评论(0编辑  收藏  举报
Live2D