大数据随笔(七):HBase安装配置和编程示例

HBase安装

首先根据hadoop版本选择合适的HBase版本。
HBase版本参考
我的hadoop是2.9.2,所以选择HBase版本是2.2.2
下载地址

tar -xzvf hbase-2.2.2-bin.tar.gz #解压
mv hbase-2.2.2 hbase #重命名
vi ~/.bashrc #添加环境变量
export PATH=${JAVA_HOME}/bin:/home/ifwant/bigData/hbase/bin$PATH #修改.bashrc,添加环境变量
source ~/.bashrc #重启使环境变量生效
hbase version #查看版本看是否安装成功

可能遇到的bug

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/ifwant/bigData/hadoop-2.9.2/share/hadoop/common/lib/slf4j-log4j12-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/ifwant/bigData/hbase/lib/client-facing-thirdparty/slf4j-log4j12-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]

hadoop和hbase的jar版本冲突,删去其中一个即可。我选择把/home/ifwant/bigData/hadoop-2.9.2/share/hadoop/common/lib下的jar包删掉。这里很奇怪的是如果删掉hbase目录下的,之后在启动hbase的时候会因为找不到StaticLoggerBinder.class而报错,所以这里先删掉hadoop下的jar包。

HBase配置

这里是伪分布式的配置
配置hbase-env.sh

vi /home/ifwant/bigData/hbase/conf/hbase-env.sh 
#将下面三句添加到sh文件里,其中HBASE_CLASSPATH目录是hadoop里hadoop-env.sh所在的目录
export JAVA_HOME=/home/ifwant/bigData/jdk1.8.0
export HBASE_CLASSPATH=/home/ifwant/bigData/hadoop-2.9.2/etc/hadoop
export HBASE_MANAGES_ZK=true

配置hbase-site.xml

vi /home/ifwant/bigData/hbase/conf/hbase-site.xml
#添加如下配置
<configuration>
    <property>
            <name>hbase.rootdir</name>
            <value>hdfs://localhost:8020/hbase</value>
    </property>
    <property>
            <name>hbase.cluster.distributed</name>
            <value>true</value>
    </property>
    <property>
            <name>hbase.unsafe.stream.capability.enforce</name>
            <value>false</value>
    </property>
</configuration>

测试运行HBase

ssh localhost #启动ssh
cd /home/ifwant/bigData/hadoop-2.9.2/sbin
./start-dfs.sh
jps #查看是否启动成功
cd /home/ifwant/bigData/hbase/bin
./start-hbase.sh
jps

出现下图就是启动成功了
在这里插入图片描述

./hbase shell #进入shell
./stop-hbase.sh #停止hbase

HBase编程实践

Shell编程

在添加数据时,HBase会自动为添加的数据添加一个时间戳,故在需要修改数据时,只需直接添加数据,HBase即会生成一个新的版本,从而完成“改”操作,旧的版本依旧保留,系统会定时回收垃圾数据,只留下最新的几个版本,保存的版本数可以在创建表的时候指定。

create 'student','Sname','Ssex','Sage','Sdept','course' #创建一个表,student是表的名称,后面几个是列族
put 'student','95001','Sname','LiYing' #为student表添加了学号为95001,名字为LiYing的一行数据,其行键为95001
put 'student','95001','course:math','80'      #math是列族下的列
delete 'student','95001','Ssex'               #删除数据
deleteall 'student','95001'                   #删除一行数据
get 'student','95001'       #查看一行数据
scan 'student'              #查看整个表的数据

#删除表分两步,先让表不可用,再删除表
disable 'student'  
drop 'student'

create 'teacher',{NAME=>'username',VERSIONS=>5}      #创建表的时候,指定保存的版本数(假设指定为5)

#插入数据并更新数据
put 'teacher','91001','username','Mary'
put 'teacher','91001','username','Mary1'
put 'teacher','91001','username','Mary2'
put 'teacher','91001','username','Mary3'
put 'teacher','91001','username','Mary4'  
put 'teacher','91001','username','Mary5'

get 'teacher','91001',{COLUMN=>'username',VERSIONS=>5}   #查看最近5个版本的数值

exit   #退出

Java编程

IDEA新建一个java项目,这里不再赘述,然后导入hbase安装目录下的lib文件夹下的jar包和lib/client-facing-thirdparty文件夹下的jar包。下面是测试程序:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import java.io.IOException;
 
public class ExampleForHbase{
    public static Configuration configuration;
    public static Connection connection;
    public static Admin admin;
 
    //主函数中的语句请逐句执行,只需删除其前的//即可,如:执行insertRow时请将其他语句注释
    public static void main(String[] args)throws IOException{
        //创建一个表,表名为Score,列族为sname,course
        createTable("Score",new String[]{"sname","course"});
 
        //在Score表中插入一条数据,其行键为95001,sname为Mary(因为sname列族下没有子列所以第四个参数为空)
        //等价命令:put 'Score','95001','sname','Mary'
        //insertRow("Score", "95001", "sname", "", "Mary");
        //在Score表中插入一条数据,其行键为95001,course:Math为88(course为列族,Math为course下的子列)
        //等价命令:put 'Score','95001','score:Math','88'
        //insertRow("Score", "95001", "course", "Math", "88");
        //在Score表中插入一条数据,其行键为95001,course:English为85(course为列族,English为course下的子列)
        //等价命令:put 'Score','95001','score:English','85'
        //insertRow("Score", "95001", "course", "English", "85");
 
        //1、删除Score表中指定列数据,其行键为95001,列族为course,列为Math
        //执行这句代码前请deleteRow方法的定义中,将删除指定列数据的代码取消注释注释,将删除制定列族的代码注释
        //等价命令:delete 'Score','95001','score:Math'
        //deleteRow("Score", "95001", "course", "Math");
 
        //2、删除Score表中指定列族数据,其行键为95001,列族为course(95001的Math和English的值都会被删除)
        //执行这句代码前请deleteRow方法的定义中,将删除指定列数据的代码注释,将删除制定列族的代码取消注释
        //等价命令:delete 'Score','95001','score'
        //deleteRow("Score", "95001", "course", "");
 
        //3、删除Score表中指定行数据,其行键为95001
        //执行这句代码前请deleteRow方法的定义中,将删除指定列数据的代码注释,以及将删除制定列族的代码注释
        //等价命令:deleteall 'Score','95001'
        //deleteRow("Score", "95001", "", "");
 
        //查询Score表中,行键为95001,列族为course,列为Math的值
        //getData("Score", "95001", "course", "Math");
        //查询Score表中,行键为95001,列族为sname的值(因为sname列族下没有子列所以第四个参数为空)
        //getData("Score", "95001", "sname", "");
 
        //删除Score表
        //deleteTable("Score");
    }
 
    //建立连接
    public static void init(){
        configuration  = HBaseConfiguration.create();
        configuration.set("hbase.rootdir","hdfs://localhost:9000/hbase");
        try{
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    //关闭连接
    public static void close(){
        try{
            if(admin != null){
                admin.close();
            }
            if(null != connection){
                connection.close();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
 
    /**
     * 建表。HBase的表中会有一个系统默认的属性作为主键,主键无需自行创建,默认为put命令操作中表名后第一个数据,因此此处无需创建id列
     * @param myTableName 表名
     * @param colFamily 列族名
     * @throws IOException
     */
    public static void createTable(String myTableName,String[] colFamily) throws IOException {
 
        init();
        TableName tableName = TableName.valueOf(myTableName);
 
        if(admin.tableExists(tableName)){
            System.out.println("talbe is exists!");
        }else {
            HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
            for(String str:colFamily){
                HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(str);
                hTableDescriptor.addFamily(hColumnDescriptor);
            }
            admin.createTable(hTableDescriptor);
            System.out.println("create table success");
        }
        close();
    }
    /**
     * 删除指定表
     * @param tableName 表名
     * @throws IOException
     */
    public static void deleteTable(String tableName) throws IOException {
        init();
        TableName tn = TableName.valueOf(tableName);
        if (admin.tableExists(tn)) {
            admin.disableTable(tn);
            admin.deleteTable(tn);
        }
        close();
    }
 
    /**
     * 查看已有表
     * @throws IOException
     */
    public static void listTables() throws IOException {
        init();
        HTableDescriptor hTableDescriptors[] = admin.listTables();
        for(HTableDescriptor hTableDescriptor :hTableDescriptors){
            System.out.println(hTableDescriptor.getNameAsString());
        }
        close();
    }
    /**
     * 向某一行的某一列插入数据
     * @param tableName 表名
     * @param rowKey 行键
     * @param colFamily 列族名
     * @param col 列名(如果其列族下没有子列,此参数可为空)
     * @param val 值
     * @throws IOException
     */
    public static void insertRow(String tableName,String rowKey,String colFamily,String col,String val) throws IOException {
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Put put = new Put(rowKey.getBytes());
        put.addColumn(colFamily.getBytes(), col.getBytes(), val.getBytes());
        table.put(put);
        table.close();
        close();
    }
 
    /**
     * 删除数据
     * @param tableName 表名
     * @param rowKey 行键
     * @param colFamily 列族名
     * @param col 列名
     * @throws IOException
     */
    public static void deleteRow(String tableName,String rowKey,String colFamily,String col) throws IOException {
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Delete delete = new Delete(rowKey.getBytes());
        //删除指定列族的所有数据
        //delete.addFamily(colFamily.getBytes());
        //删除指定列的数据
        //delete.addColumn(colFamily.getBytes(), col.getBytes());
 
        table.delete(delete);
        table.close();
        close();
    }
    /**
     * 根据行键rowkey查找数据
     * @param tableName 表名
     * @param rowKey 行键
     * @param colFamily 列族名
     * @param col 列名
     * @throws IOException
     */
    public static void getData(String tableName,String rowKey,String colFamily,String col)throws  IOException{
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Get get = new Get(rowKey.getBytes());
        get.addColumn(colFamily.getBytes(),col.getBytes());
        Result result = table.get(get);
        showCell(result);
        table.close();
        close();
    }
    /**
     * 格式化输出
     * @param result
     */
    public static void showCell(Result result){
        Cell[] cells = result.rawCells();
        for(Cell cell:cells){
            System.out.println("RowName:"+new String(CellUtil.cloneRow(cell))+" ");
            System.out.println("Timetamp:"+cell.getTimestamp()+" ");
            System.out.println("column Family:"+new String(CellUtil.cloneFamily(cell))+" ");
            System.out.println("row Name:"+new String(CellUtil.cloneQualifier(cell))+" ");
            System.out.println("value:"+new String(CellUtil.cloneValue(cell))+" ");
        }
    }
}

执行完后可以到shell中看结果。

参考资料:http://dblab.xmu.edu.cn/blog/install-hbase/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值