美文网首页
二、HBase部署与使用

二、HBase部署与使用

作者: 码农GG | 来源:发表于2019-12-16 17:56 被阅读0次

    2.1、部署

    2.1.1、Zookeeper正常部署

    首先保证Zookeeper集群的正常部署,并启动之:

    /opt/module/zookeeper-3.4.5/bin/zkServer.sh start

    2.1.2、Hadoop正常部署

    Hadoop集群的正常部署并启动:

    /opt/module/hadoop-2.8.4/sbin/start-dfs.sh

    /opt/module/hadoop-2.8.4/sbin/start-yarn.sh

    2.1.3、HBase的解压

    解压HBase到指定目录:

    tar -zxf /opt/software/hbase-1.3.1-bin.tar.gz -C /opt/module/

    2.1.4、HBase的配置文件

    需要修改HBase对应的配置文件。

    hbase-env.sh修改内容:

    export JAVA_HOME=/opt/module/jdk1.8.0_144

    export HBASE_MANAGES_ZK=false

    尖叫提示:如果使用的是JDK8以上版本,注释掉hbase-env.sh的45-47行,不然会报警告


    图片1.png

    hbase-site.xml修改内容:

    <property>  
    
    <name>hbase.rootdir</name>  
    
    <value>hdfs://bigdata111:9000/hbase</value>  
    
    </property>
    
    <property>
    
    <name>hbase.cluster.distributed</name>
    
    <value>true</value>
    
    </property>
    
    <property>
    
    <name>hbase.master.port</name>
    
    <value>16000</value>
    
    </property>
    
    <property>  
    
    <name>hbase.zookeeper.quorum</name>
    
    <value>bigdata111:2181,bigdata112:2181,bigdata113:2181</value>
    
    </property>
    
    <property>  
    
    <name>hbase.zookeeper.property.dataDir</name>
    
     <value>/opt/module/zookeeper-3.4.10/zkData</value>
    
    </property>
    
    <property>
    
    <name>hbase.master.maxclockskew</name>
    
    <value>180000</value>
    
    </property>
    

    regionservers:

    bigdata111

    bigdata112

    bigdata113

    2.1.5、HBase需要依赖的Jar包(额外,不用配置)

    由于HBase需要依赖Hadoop,所以替换HBase的lib目录下的jar包,以解决兼容问题:

    1. 删除原有的jar:

    rm -rf /opt/module/hbase-1.3.1/lib/hadoop-*

    rm -rf /opt/module/hbase-1.3.1/lib/zookeeper-3.4.10.jar

    1. 拷贝新jar,涉及的jar有:

    hadoop-annotations-2.8.4.jar

    hadoop-auth-2.8.4.jar

    hadoop-client-2.8.4.jar

    hadoop-common-2.8.4.jar

    hadoop-hdfs-2.8.4.jar

    hadoop-mapreduce-client-app-2.8.4.jar

    hadoop-mapreduce-client-common-2.8.4.jar

    hadoop-mapreduce-client-core-2.8.4.jar

    hadoop-mapreduce-client-hs-2.8.4.jar

    hadoop-mapreduce-client-hs-plugins-2.8.4.jar

    hadoop-mapreduce-client-jobclient-2.8.4.jar

    hadoop-mapreduce-client-jobclient-2.8.4-tests.jar

    hadoop-mapreduce-client-shuffle-2.8.4.jar

    hadoop-yarn-api-2.8.4.jar

    hadoop-yarn-applications-distributedshell-2.8.4.jar

    hadoop-yarn-applications-unmanaged-am-launcher-2.8.4.jar

    hadoop-yarn-client-2.8.4.jar

    hadoop-yarn-common-2.8.4.jar

    hadoop-yarn-server-applicationhistoryservice-2.8.4.jar

    hadoop-yarn-server-common-2.8.4.jar

    hadoop-yarn-server-nodemanager-2.8.4.jar

    hadoop-yarn-server-resourcemanager-2.8.4.jar

    hadoop-yarn-server-tests-2.8.4.jar

    hadoop-yarn-server-web-proxy-2.8.4.jar

    zookeeper-3.4.10.jar

    尖叫提示:这些jar包的对应版本应替换成你目前使用的hadoop版本,具体情况具体分析。

    查找jar包举例:

    find /opt/module/hadoop-2.8.4/ -name hadoop-annotations*

    然后将找到的jar包复制到HBase的lib目录下即可。

    2.1.6、HBase软连接Hadoop配置(额外,不用配置)

    ln -s /opt/module/hadoop-2.8.4/etc/hadoop/core-site.xml /opt/module/hbase-1.3.1/conf/core-site.xml

    ln -s /opt/module/hadoop-2.8.4/etc/hadoop/hdfs-site.xml /opt/module/hbase-1.3.1/conf/hdfs-site.xml

    2.1.7.0 配置环境变量

    vi /etc/profile
    
    export HBASE_HOME=/opt/module/hbase-1.3.1
    
    export PATH=$HBASE_HOME/bin:$PATH
    
    source /etc/profile
    

    2.1.7.1 HBase远程scp到其他集群

    scp -r /opt/module/hbase-1.3.1/ bigdata112:/opt/module/
    
    scp -r /opt/module/hbase-1.3.1/ bigdata113:/opt/module/
    

    2.1.8、HBase服务的启动

    启动方式1:

    bin/hbase-daemon.sh start master
    
    bin/hbase-daemon.sh start regionserver
    

    尖叫提示:如果集群之间的节点时间不同步,会导致regionserver无法启动,抛出ClockOutOfSyncException异常。

    启动方式2:

    bin/start-hbase.sh

    对应的停止服务:

    bin/stop-hbase.sh

    注:如果需要清理Hbase,需要做如下的事情

    1. 删除HDFS的/hbase目录

    2. 删除ZK的/hbase节点

    3. 删除/opt/module/hbase-1.3.1目录

    2.1.9、查看Hbase页面

    启动成功后,可以通过“host:port”的方式来访问HBase管理页面,例如:

    http://bigdata111:16010

    2.2 基本操作

    1. 进入HBase客户端命令行

    bin/hbase shell

    2) 查看帮助命令

    hbase(main)> help

    3) 查看当前数据库中有哪些表

    hbase(main)> list

    4) 查看当前数据库中有哪些命名空间

    hbase(main)> list_namespace

    2.2.1 表的操作

    1. 创建表
    hbase(main)> create 'student','cf1'
    
    hbase(main)> create 'iparkmerchant_order','smzf'
    
    hbase(main)> create 'staff','info'
    

    2) 插入数据到表

    hbase(main) > put 'student','1001','cf1:name','Thomas'
    
    hbase(main) > put 'student','1001','cf1:sex','male'
    
    hbase(main) > put 'student','1001','cf1:age','18'
    
    hbase(main) > put 'student','1002','cf1:name','Janna'
    
    hbase(main) > put 'student','1002','cf1:sex','female'
    
    hbase(main) > put 'student','1002','cf1:age','20'
    

    数据插入后的数据模型


    image.png

    3) 扫描查看表数据

    hbase(main) > scan 'student'
    
    hbase(main) > scan 'student',{STARTROW => '1001', STOPROW  => '1001'}
    
    hbase(main) > scan 'student',{STARTROW => '1001'}
    

    注:这个是从哪一个rowkey开始扫描

    4) 查看表结构

    hbase(main):012:0> desc 'student'
    

    5) 更新指定字段的数据

    hbase(main) > put 'student','1001','cf1:name','Nick'
    
    hbase(main) > put 'student','1001','cf1:age','100'
    
    hbase(main) > put 'student','1001','cf1:isNull',''(仅测试空值问题)
    

    6) 查看“指定行”或“指定列族:列”的数据

    hbase(main) > get 'student','1001'
    
    hbase(main) > get 'student','1001','cf1:name'
    

    7) 删除数据

    删除某rowkey的全部数据:

    hbase(main) > deleteall 'student','1001'
    

    8) 清空表数据

    hbase(main) > truncate 'student'
    

    尖叫提示:清空表的操作顺序为先disable,然后再truncate。

    9) 删除表

    首先需要先让该表为disable状态:

    hbase(main) > disable 'student'

    检查这个表是否被禁用

    hbase(main) > is_enabled 'hbase_book'

    hbase(main) > is_disabled 'hbase_book'

    恢复被禁用得表

    enable 'student'

    然后才能drop这个表:

    hbase(main) > drop 'student'

    尖叫提示:如果直接drop表,会报错:Drop the named table. Table must first be disabled

    ERROR: Table student is enabled. Disable it first.

    10) 统计表数据行数

    hbase(main) > count 'student'

    11) 变更表信息

    将info列族中的数据存放3个版本:

    hbase(main) > alter 'student',{NAME=>'info',VERSIONS=>3}

    查看student的最新的版本的数据

    hbase(main) > get 'student','1001'

    查看HBase中的多版本

    hbase(main) > get 'student','1001',{COLUMN=>'info:name',VERSIONS=>10}

    2.2.2 常用Shell操作

    1) satus 例如:显示服务器状态

    hbase> status 'bigdata111'

    2) exists检查表是否存在,适用于表量特别多的情况

    hbase> exists 'hbase_book'

    3) is_enabled/is_disabled 检查表是否启用或禁用

    hbase> is_enabled 'hbase_book'

    hbase> is_disabled 'hbase_book'

    8) alter 该命令可以改变表和列族的模式,例如:

    为当前表增加列族:

    hbase> alter 'hbase_book', NAME => 'CF2', VERSIONS => 2

    为当前表删除列族:

    hbase> alter 'hbase_book', 'delete' => 'CF2'

    9) disable禁用一张表

    hbase> disable 'hbase_book'

    hbase> drop 'hbase_book'

    10) delete

    删除一行中一个单元格的值,例如:

    hbase> delete 'hbase_book', 'rowKey', 'CF:C'

    11) truncate清空表数据,即禁用表-删除表-创建表

    hbase> truncate 'hbase_book'

    12) create

    创建多个列族:

    hbase> create 't1', {NAME => 'f1'}, {NAME => 'f2'}, {NAME => 'f3'}

    2.3、读写流程

    2.3.1、HBase读数据流程

    Hbase的regionserver的内存Memstore,block cache。Memstore作业主要是写,另一部分主要是读的。block cache用的是Least Recently Used(LRU),如果block cache达到上限,会启动淘汰机制。

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

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

    3. Client通过元数据中存储的信息,访问对应的HRegionServer,然后扫描(scan)所在

    HRegionServer的Memstore如果没有,扫描block cache(读数据的缓存),如果还没有去Storefile来查询数据,查到数据之后将数据读到block cache。

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

    2.3.2、HBase写数据流程

    1. Client也是先访问zookeeper,进而找到.META.表,并获取.META.表信息。

    2. 确定当前将要写入的数据所对应的RegionServer服务器和Region。

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

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

    5. 然后将数据写入到Memstore。

    6. 如果Hlog和Memstore均写入成功,则这条数据写入成功。在此过程中,如果Memstore达到阈值,会把Memstore中的数据flush到StoreFile中。

    7. 当Storefile越来越多,会触发Compact合并操作,把过多的Storefile合并成一个大的Storefile。当Storefile越来越大,Region也会越来越大,达到阈值后,会触发Split操作,将Region一分为二。

    尖叫提示:因为内存空间是有限的,所以说溢写过程必定伴随着大量的小文件产生。

    2.4、JavaAPI

    2.4.1 新建Maven Project

    新建项目后在pom.xml中添加依赖:

    <dependency>
    
    <groupId>org.apache.hbase</groupId>
    
    <artifactId>hbase-server</artifactId>
    
    <version>1.3.1</version>
    
    </dependency>
    
    <dependency>
    
    <groupId>org.apache.hbase</groupId>
    
    <artifactId>hbase-client</artifactId>
    
    <version>1.3.1</version>
    
    </dependency>
    

    2.4.2 编写HBaseAPI

    注意,这部分的学习内容,我们先学习使用老版本的API,接着再写出新版本的API调用方式。因为在企业中,有些时候我们需要一些过时的API来提供更好的兼容性。

    1) 首先需要获取Configuration对象:

    public static Configuration conf;
    
    static{
    
    //使用HBaseConfiguration的单例方法实例化
    
    conf = HBaseConfiguration.create();
    
    conf.set("hbase.zookeeper.quorum", "bigdata111");
    
    conf.set("hbase.zookeeper.property.clientPort", "2181");
    
    conf.set("zookeeper.znode.parent", "/hbase");
    
    }
    

    2) 判断表是否存在:

    public static boolean isTableExist(String tableName) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{
    
    //在HBase中管理、访问表需要先创建HBaseAdmin对象
    
    Connection connection = ConnectionFactory.createConnection(conf);
    
    HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();
    
    //HBaseAdmin admin = new HBaseAdmin(conf);
    
    return admin.tableExists(tableName);
    
    }
    

    3) 创建表

    public static void createTable(String tableName, String... columnFamily) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{
    
    HBaseAdmin admin = new HBaseAdmin(conf);
    
    //判断表是否存在
    
    if(isTableExist(tableName)){
    
    System.out.println("表" + tableName + "已存在");
    
    //System.exit(0);
    
    }else{
    
    //创建表属性对象,表名需要转字节
    
    HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(tableName));
    
    //创建多个列族
    
    for(String cf : columnFamily){
    
    descriptor.addFamily(new HColumnDescriptor(cf));
    
    }
    
    //根据对表的配置,创建表
    
    admin.createTable(descriptor);
    
    System.out.println("表" + tableName + "创建成功!");
    
    }
    
    }
    

    4) 删除表

    public static void dropTable(String tableName) throws Exception{
    
    HBaseAdmin admin = new HBaseAdmin(conf);
    
    if(isTableExist(tableName)){
    
    admin.disableTable(tableName);
    
    admin.deleteTable(tableName);
    
    System.out.println("表" + tableName + "删除成功!");
    
    }else{
    
    System.out.println("表" + tableName + "不存在!");
    
    }
    
    }
    

    5) 向表中插入数据

    public static void addRowData(String tableName, String rowKey, String columnFamily, String column, String value) throws Exception{
    
    //创建HTable对象
    
    HTable hTable = new HTable(conf, tableName);
    
    //向表中插入数据
    
    Put put = new Put(Bytes.toBytes(rowKey));
    
    //向Put对象中组装数据
    
    put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value));
    
    hTable.put(put);
    
    hTable.close();
    
    System.out.println("插入数据成功");
    
    }
    

    6) 删除多行数据

    public static void deleteMultiRow(String tableName, String... rows) throws IOException{
    
    HTable hTable = new HTable(conf, tableName);
    
    List<Delete> deleteList = new ArrayList<Delete>();
    
    for(String row : rows){
    
    Delete delete = new Delete(Bytes.toBytes(row));
    
    deleteList.add(delete);
    
    }
    
    hTable.delete(deleteList);
    
    hTable.close();
    
    }
    

    7) 得到所有数据

    public static void getAllRows(String tableName) throws IOException{
    
    HTable hTable = new HTable(conf, tableName);
    
    //得到用于扫描region的对象
    
    Scan scan = new Scan();
    
    //使用HTable得到resultcanner实现类的对象
    
    ResultScanner resultScanner = hTable.getScanner(scan);
    
    for(Result result : resultScanner){
    
    Cell[] cells = result.rawCells();
    
    for(Cell cell : cells){
    
    //得到rowkey
    
    System.out.println("行键:" + Bytes.toString(CellUtil.cloneRow(cell)));
    
    //得到列族
    
    System.out.println("列族" + Bytes.toString(CellUtil.cloneFamily(cell)));
    
    System.out.println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)));
    
    System.out.println("值:" + Bytes.toString(CellUtil.cloneValue(cell)));
    
    }
    
    }
    
    }
    

    8) 得到某一行所有数据

    public static void getRow(String tableName, String rowKey) throws IOException{
    
    HTable table = new HTable(conf, tableName);
    
    Get get = new Get(Bytes.toBytes(rowKey));
    
    //get.setMaxVersions();显示所有版本
    
    //get.setTimeStamp();显示指定时间戳的版本
    
    Result result = table.get(get);
    
    for(Cell cell : result.rawCells()){
    
    System.out.println("行键:" + Bytes.toString(result.getRow()));
    
    System.out.println("列族" + Bytes.toString(CellUtil.cloneFamily(cell)));
    
    System.out.println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)));
    
    System.out.println("值:" + Bytes.toString(CellUtil.cloneValue(cell)));
    
    System.out.println("时间戳:" + cell.getTimestamp());
    
    }
    
    }
    

    9) 获取某一行指定“列族:列”的数据

    public static void getRowQualifier(String tableName, String rowKey, String family, String qualifier) throws IOException{
    
    HTable table = new HTable(conf, tableName);
    
    Get get = new Get(Bytes.toBytes(rowKey));
    
    get.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
    
    Result result = table.get(get);
    
    for(Cell cell : result.rawCells()){
    
    System.out.println("行键:" + Bytes.toString(result.getRow()));
    
    System.out.println("列族" + Bytes.toString(CellUtil.cloneFamily(cell)));
    
    System.out.println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)));
    
    System.out.println("值:" + Bytes.toString(CellUtil.cloneValue(cell)));
    
    }
    
    }
    

    2.4.3 HBaseUtil

    import org.apache.hadoop.conf.Configuration;
    
    import org.apache.hadoop.hbase.HColumnDescriptor;
    
    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.apache.hadoop.hbase.client.ConnectionFactory;
    
    import org.apache.hadoop.hbase.util.Bytes;
    
    import java.io.IOException;
    
    import java.text.DecimalFormat;
    
    import java.util.Iterator;
    
    import java.util.TreeSet;
    
    /**
    
    * @author Andy
    
    * 1、NameSpace ====>  命名空间
    
    * 2、createTable ===> 表
    
    * 3、isTable   ====>  判断表是否存在
    
    * 4、Region、RowKey、分区键
    
    */
    
    public class HBaseUtil {
    
    /**
    
    * 初始化命名空间
    
    *
    
    * @param conf      配置对象
    
    * @param namespace 命名空间的名字
    
    * @throws Exception
    
    */
    
    public static void initNameSpace(Configuration conf, String namespace) throws Exception {
    
    Connection connection = ConnectionFactory.createConnection(conf);
    
    Admin admin = connection.getAdmin();
    
    //命名空间描述器
    
    NamespaceDescriptor nd = NamespaceDescriptor
    
    .create(namespace)
    
    .addConfiguration("AUTHOR", "plus")
    
    .build();
    
    //通过admin对象来创建命名空间
    
    admin.createNamespace(nd);
    
    System.out.println("已初始化命名空间");
    
    //关闭两个对象
    
    close(admin, connection);
    
    }
    
    /**
    
    * 关闭admin对象和connection对象
    
    *
    
    * @param admin      关闭admin对象
    
    * @param connection 关闭connection对象
    
    * @throws IOException IO异常
    
    */
    
    private static void close(Admin admin, Connection connection) throws IOException {
    
    if (admin != null) {
    
    admin.close();
    
    }
    
    if (connection != null) {
    
    connection.close();
    
    }
    
    }
    
    /**
    
    * 创建HBase的表
    
    * @param conf
    
    * @param tableName
    
    * @param regions
    
    * @param columnFamily
    
    */
    
    public static void createTable(Configuration conf, String tableName, int regions, String... columnFamily) throws IOException {
    
    Connection connection = ConnectionFactory.createConnection(conf);
    
    Admin admin = connection.getAdmin();
    
    //判断表
    
    if (isExistTable(conf, tableName)) {
    
    return;
    
    }
    
    //表描述器 HTableDescriptor
    
    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName));
    
    for (String cf : columnFamily) {
    
    //列描述器 :HColumnDescriptor
    
    htd.addFamily(new HColumnDescriptor(cf));
    
    }
    
    //htd.addCoprocessor("hbase.CalleeWriteObserver");
    
    //创建表
    
    admin.createTable(htd,genSplitKeys(regions));
    
    System.out.println("已建表");
    
    //关闭对象
    
    close(admin,connection);
    
    }
    
    /**
    
    * 分区键
    
    * @param regions region个数
    
    * @return splitKeys
    
    */
    
    private static byte[][] genSplitKeys(int regions) {
    
    //存放分区键的数组
    
    String[] keys = new String[regions];
    
    //格式化分区键的形式  00 01 02
    
    DecimalFormat df = new DecimalFormat("00");
    
    for (int i = 0; i < regions; i++) {
    
    keys[i] = df.format(i) + "";
    
    }
    
    byte[][] splitKeys = new byte[regions][];
    
    //排序 保证你这个分区键是有序得
    
    TreeSet<byte[]> treeSet = new TreeSet<>(Bytes.BYTES_COMPARATOR);
    
    for (int i = 0; i < regions; i++) {
    
    treeSet.add(Bytes.toBytes(keys[i]));
    
    }
    
    //输出
    
    Iterator<byte[]> iterator = treeSet.iterator();
    
    int index = 0;
    
    while (iterator.hasNext()) {
    
    byte[] next = iterator.next();
    
    splitKeys[index++]= next;
    
    }
    
    return splitKeys;
    
    }
    
    /**
    
    * 判断表是否存在
    
    * @param conf      配置 conf
    
    * @param tableName 表名
    
    */
    
    public static boolean isExistTable(Configuration conf, String tableName) throws IOException {
    
    Connection connection = ConnectionFactory.createConnection(conf);
    
    Admin admin = connection.getAdmin();
    
    boolean result = admin.tableExists(TableName.valueOf(tableName));
    
    close(admin, connection);
    
    return result;
    
    }
    
    }
    

    2.4.4 PropertiesUtil

    import java.io.IOException;
    
    import java.io.InputStream;
    
    import java.util.Properties;
    
    public class PropertiesUtil {
    
    public static Properties properties = null;
    
    static {
    
    //获取配置文件、方便维护
    
    InputStream is = ClassLoader.getSystemResourceAsStream("hbase_consumer.properties");
    
    properties = new Properties();
    
    try {
    
    properties.load(is);
    
    } catch (IOException e) {
    
    e.printStackTrace();
    
    }
    
    }
    
    /**
    
    * 获取参数值
    
    * @param key 名字
    
    * @return 参数值
    
    */
    
    public static String getProperty(String key){
    
    return properties.getProperty(key);
    
    }
    
    }
    

    2.4.5 HBaseDAO

    import org.apache.hadoop.conf.Configuration;
    
    import org.apache.hadoop.hbase.HBaseConfiguration;
    
    public class HBaseDAO {
    
    private static String namespace = PropertiesUtil.getProperty("hbase.calllog.namespace");
    
    private static String tableName = PropertiesUtil.getProperty("hbase.calllog.tablename");
    
    private static Integer regions = Integer.valueOf(PropertiesUtil.getProperty("hbase.calllog.regions"));
    
    public static void main(String[] args) throws Exception {
    
    Configuration conf = HBaseConfiguration.create();
    
    conf.set("hbase.zookeeper.property.clientPort", "2181");
    
    conf.set("hbase.zookeeper.quorum", "bigdata111");
    
    conf.set("zookeeper.znode.parent", "/hbase");
    
    if (!HBaseUtil.isExistTable(conf, tableName)) {
    
    HBaseUtil.initNameSpace(conf, namespace);
    
    HBaseUtil.createTable(conf, tableName, regions, "f1", "f2");
    
    }
    
    }
    

    2.5、MapReduce

    通过HBase的相关JavaAPI,我们可以实现伴随HBase操作的MapReduce过程,比如使用MapReduce将数据从本地文件系统导入到HBase的表中,比如我们从HBase中读取一些原始数据后使用MapReduce做数据分析。

    2.5、官方HBase-MapReduce

    1) 查看HBase的MapReduce任务的所需的依赖

    $ bin/hbase mapredcp

    2) 执行环境变量的导入

    export HBASE_HOME=/opt/module/hbase-1.3.1

    export HADOOP_CLASSPATH=${HBASE_HOME}/bin/hbase mapredcp

    3) 运行官方的MapReduce任务

    -- 案例一:统计Student表中有多少行数据

    /opt/module/hadoop-2.8.4/bin/yarn jar /opt/module/hbase-1.3.1/lib/hbase-server-1.3.1.jar rowcounter andy


    图片2.png

    -- 案例二:使用MapReduce将本地数据导入到HBase

    (1) 在本地创建一个tsv格式的文件:city.tsv,自己建表用\t分割数据

    1001 BeiJing China

    1002 New York TUS

    1003 ShangHai China

    尖叫提示:上面的这个数据不要从word中直接复制,有格式错误

    (2) 创建HBase表

    hbase(main):001:0> create 'city','cf'

    (3) 在HDFS中创建input_fruit文件夹并上传city.tsv文件

    $ /opt/module/hadoop-2.8.4/bin/hdfs dfs -mkdir /hbase_test/

    $ /opt/module/hadoop-2.8.4/bin/hdfs dfs -put city.tsv /hbase_test/

    (4) 执行MapReduce到HBase的fruit表中

    /opt/module/hadoop-2.8.4/bin/yarn jar /opt/module/hbase-1.3.1/lib/hbase-server-1.3.1.jar importtsv \

    -Dimporttsv.columns=HBASE_ROW_KEY,cf:name,cf:countries city \

    hdfs://bigdata111:9000/hbase_test

    (5) 使用scan命令查看导入后的结果

    hbase(main):001:0> scan 'city'

    2.5.1、HBase2HBase

    目标:将fruit表中的一部分数据,通过MR迁入到city_mr表中。

    分步实现:

    1) 构建ReadCityMapper类,用于读取city表中的数据

    [图片上传失败...(image-c00c24-1576421748779)] [图片上传失败...(image-9dce37-1576421748779)] [图片上传失败...(image-186f32-1576421748779)]

    /opt/module/hadoop-2.8.4/bin/yarn jar HBaseDemo-1.0-SNAPSHOT.jar HBase2HBase.City2CityDriver
    
    

    尖叫提示:运行任务前,如果待数据导入的表不存在,则需要提前创建之。

    2.5.2、HDFS2HBase

    目标:实现将HDFS中的数据写入到HBase表中。

    分步实现:

    1) 构建ReadFruitFromHDFSMapper于读取HDFS中的文件数据

    [图片上传失败...(image-756059-1576421748779)] [图片上传失败...(image-5c8f6d-1576421748779)] [图片上传失败...(image-c14268-1576421748779)]

    /opt/module/hadoop-2.8.4/bin/yarn jar HBaseDemo-1.0-SNAPSHOT.jar HDFS2HBase.HDFS2HBaseDriver
    
    

    尖叫提示:运行任务前,如果待数据导入的表不存在,则需要提前创建之。

    2.6、与Hive的集成

    2.6.1、HBase与Hive的对比

    image.png

    2.6.2、HBase与Hive集成使用

    环境准备

    因为我们后续可能会在操作Hive的同时对HBase也会产生影响,所以Hive需要持有操作HBase的Jar,那么接下来拷贝Hive所依赖的Jar包(或者使用软连接的形式)。记得还有把zookeeper的jar包考入到hive的lib目录下。

    环境变量/etc/profile

    $ export HBASE_HOME=/opt/module/hbase-1.3.1
    
    $ export HIVE_HOME=/opt/module/hive
    

    Shell执行

    ln -s $HBASE_HOME/lib/hbase-common-1.3.1.jar  $HIVE_HOME/lib/hbase-common-1.3.1.jar
    
    ln -s $HBASE_HOME/lib/hbase-server-1.3.1.jar $HIVE_HOME/lib/hbase-server-1.3.1.jar
    
    ln -s $HBASE_HOME/lib/hbase-client-1.3.1.jar $HIVE_HOME/lib/hbase-client-1.3.1.jar
    
    ln -s $HBASE_HOME/lib/hbase-protocol-1.3.1.jar $HIVE_HOME/lib/hbase-protocol-1.3.1.jar
    
    ln -s $HBASE_HOME/lib/hbase-it-1.3.1.jar $HIVE_HOME/lib/hbase-it-1.3.1.jar
    
    ln -s $HBASE_HOME/lib/htrace-core-3.1.0-incubating.jar $HIVE_HOME/lib/htrace-core-3.1.0-incubating.jar
    
    ln -s $HBASE_HOME/lib/hbase-hadoop2-compat-1.3.1.jar $HIVE_HOME/lib/hbase-hadoop2-compat-1.3.1.jar
    
    ln -s $HBASE_HOME/lib/hbase-hadoop-compat-1.3.1.jar $HIVE_HOME/lib/hbase-hadoop-compat-1.3.1.jar
    

    同时在hive-site.xml中修改zookeeper的属性,如下:

    <property>
    
    <name>hive.zookeeper.quorum</name>
    
    <value>bigdata111,bigdata112,bigdata113</value>
    
    <description>The list of ZooKeeper servers to talk to. This is only needed for read/write locks.</description>
    
    </property>
    
    <property>
    
    <name>hive.zookeeper.client.port</name>
    
    <value>2181</value>
    
    <description>The port of ZooKeeper servers to talk to. This is only needed for read/write locks.</description>
    
    </property>
    

    1) 案例一

    目标:建立Hive表,关联HBase表,插入数据到Hive表的同时能够影响HBase表。

    分步实现:

    (1) 在Hive中创建表同时关联HBase

    CREATE TABLE hive_hbase_emp_table(
    
    empno int,
    
    ename string,
    
    job string,
    
    mgr int,
    
    hiredate string,
    
    sal double,
    
    comm double,
    
    deptno int)
    
    STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler'
    
    WITH SERDEPROPERTIES ("hbase.columns.mapping" = ":key,info:ename,info:job,info:mgr,info:hiredate,info:sal,info:comm,info:deptno");
    
    TBLPROPERTIES ("hbase.table.name" = "hbase_emp_table");
    

    尖叫提示:完成之后,可以分别进入Hive和HBase查看,都生成了对应的表

    运行出错:需要更换hive的lib目录下的<u>hive-hbase-handler-1.2.1.jar</u>

    (2) 在Hive中创建临时中间表,用于load文件中的数据

    尖叫提示:不能将数据直接load进Hive所关联HBase的那张表中

    
    CREATE TABLE hive_hbase_emp(
    
    empno int,
    
    ename string,
    
    job string,
    
    mgr int,
    
    hiredate string,
    
    sal double,
    
    comm double,
    
    deptno int)
    
    row format delimited fields terminated by '\t';
    
    

    (3) 向Hive中间表中load数据

    
    hive> load data local inpath '/opt/module/datas/emp.txt' into table hive_hbase_emp;
    
    

    (4) 通过insert命令将中间表中的数据导入到Hive关联HBase的那张表中

    
    hive> insert into table hive_hbase_emp_table select * from hive_hbase_emp;
    
    

    (5) 查看Hive以及关联的HBase表中是否已经成功的同步插入了数据

    Hive:

    
    hive> select * from hive_hbase_emp_table;
    
    

    HBase:

    
    hbase> scan 'hbase_emp_table'
    
    

    2) 案例二

    目标:在HBase中已经存储了某一张表hbase_emp_table,然后在Hive中创建一个外部表来关联HBase中的hbase_emp_table这张表,使之可以借助Hive来分析HBase这张表中的数据。

    注:该案例2紧跟案例1的脚步,所以完成此案例前,请先完成案例1。

    分步实现:

    (1) 在Hive中创建外部表

    
    CREATE EXTERNAL TABLE relevance_hbase_emp1(
    
    empno int,
    
    ename string,
    
    job string,
    
    mgr int,
    
    hiredate string,
    
    sal double,
    
    comm double,
    
    deptno int)
    
    STORED BY
    
    'org.apache.hadoop.hive.hbase.HBaseStorageHandler'
    
    WITH SERDEPROPERTIES ("hbase.columns.mapping" =
    
    ":key,info:ename,info:job,info:mgr,info:hiredate,info:sal,info:comm,info:deptno")
    
    TBLPROPERTIES ("hbase.table.name" = "hbase_emp_table");
    
    

    (2) 关联后就可以使用Hive函数进行一些分析操作了

    
    hive (default)> select * from relevance_hbase_emp;
    
    

    2.7、Sqoop集成:MySQL TO HBase

    Sqoop supports additional import targets beyond HDFS and Hive. Sqoop can also import records into a table in HBase.

    之前我们已经学习过如何使用Sqoop在Hadoop集群和关系型数据库中进行数据的导入导出工作,接下来我们学习一下利用Sqoop在HBase和RDBMS中进行数据的转储。

    相关参数:

    image.png

    1) 案例

    目标:将RDBMS中的数据抽取到HBase中

    分步实现:

    (1) 配置sqoop-env.sh,添加如下内容:

    
    export HBASE_HOME=/opt/module/hbase-1.3.1
    
    

    (2) 在Mysql中新建一个数据库db_library,一张表book

    
    CREATE DATABASE db_library;
    
    CREATE TABLE db_library.book(
    
    id int(4) PRIMARY KEY NOT NULL AUTO_INCREMENT,
    
    name VARCHAR(255) NOT NULL,
    
    price VARCHAR(255) NOT NULL);
    
    

    (3) 向表中插入一些数据

    
    INSERT INTO db_library.book (name, price) VALUES('Lie Sporting', '30');  
    
    INSERT INTO db_library.book (name, price) VALUES('Pride & Prejudice', '70');  
    
    INSERT INTO db_library.book (name, price) VALUES('Fall of Giants', '50');
    
    

    (4) 执行Sqoop导入数据的操作

    手动创建HBase表

    
    hbase> create 'hbase_book','info'
    
    

    (5) 在HBase中scan这张表得到如下内容

    
    hbase> scan 'hbase_book'
    
    

    思考:尝试使用复合键作为导入数据时的rowkey。

    
    $ bin/sqoop import \
    
    --connect jdbc:mysql://bigdata111:3306/db_library \
    
    --username root \
    
    --password 000000 \
    
    --table book \
    
    --columns "id,name,price" \
    
    --column-family "info" \
    
    --hbase-create-table \
    
    --hbase-row-key "id" \
    
    --hbase-table "hbase_book" \
    
    --num-mappers 1 \
    
    --split-by id
    
    

    尖叫提示:sqoop1.4.6只支持HBase1.0.1之前的版本的自动创建HBase表的功能

    2.9 Phoenix集成

    1. Phoenix介绍

    可以把Phoenix理解为Hbase的查询引擎,phoenix,由saleforce.com开源的一个项目,后又捐给了Apache。它相当于一个Java中间件,帮助开发者,像使用jdbc访问关系型数据库一样,访问NoSql数据库HBase。

    phoenix,操作的表及数据,存储在hbase上。phoenix只是需要和Hbase进行表关联起来。然后再用工具进行一些读或写操作。

    其实,可以把Phoenix只看成一种代替HBase的语法的一个工具。虽然可以用java可以用jdbc来连接phoenix,然后操作HBase,但是在生产环境中,不可以用在OLTP中。在线事务处理的环境中,需要低延迟,而Phoenix在查询HBase时,虽然做了一些优化,但延迟还是不小。所以依然是用在OLAT中,再将结果返回存储下来。

    2.phoenix安装包解压缩更换目录

    tar -zxvf apache-phoenix-4.14.1-HBase-1.3-bin.tar.gz -C /opt/module

    mv apache-phoenix-4.14.1-HBase-1.3-bin phoenix-4.14.1

    环境变量vi /etc/profile

    在最后两行加上如下phoenix配置

    export PHOENIX_HOME=/opt/module/phoenix-4.14.1

    export PATH=PATH:PHOENIX_HOME/bin

    使环境变量配置生效

    source /etc/profile

    将主节点的phoenix包传到从节点

    scp -r phoenix-4.14.1 root@bigdata113:/opt/module

    scp -r phoenix-4.14.1 root@bigdata112:/opt/module

    拷贝hbase-site.xml(注)三台都要

    cp hbase-site.xml /opt/module/phoenix-4.14.1/bin/

    将如下两个jar包,目录在/opt/module/phoenix-4.14.1下,拷贝到hbase的lib目录,目录在/opt/module/hbase-1.3.1/lib/

    (注)三台都要

    phoenix-4.14.1-HBase-1.3-server.jar

    phoenix-core-4.14.1-HBase-1.3.jar

    启动Phoenix

    配置好之后重启下hbase。

    sqlline.py bigdata111:2181

    [图片上传失败...(image-261f5e-1576421748785)]

    基本命令

    展示表

    !table

    创建表

    create table test(id integer not null primary key,name varchar);

    create table "plus"(

    id integer not null primary key,

    name varchar);

    删除表

    drop table test;

    插入数据

    upsert into test values(1,'plus');

    upsert into users(name) values('toms');

    查询数据

    phoenix > select * from test;

    hbase > scan 'test'

    退出phoenix

    !q

    删除数据

    delete from "Andy" where id=4;

    sum函数的使用

    select sum(id) from "Andy";

    增加一列

    alter table "Andy" add address varchar;

    删除一列

    alter table "Andy" drop column address;

    其他语法详见:<u>http://phoenix.apache.org/language/index.html</u>

    表映射

    hbase中创建表

    create 'teacher1','info','contact'

    插入数据

    put 'teacher1','1001','info:name','Jack'

    put 'teacher1','1001','info:age','28'

    put 'teacher1','1001','info:gender','male'

    put 'teacher1','1001','contact:address','shanghai'

    put 'teacher1','1001','contact:phone','13458646987'

    put 'teacher1','1002','info:name','Jim'

    put 'teacher1','1002','info:age','30'

    put 'teacher1','1002','info:gender','male'

    put 'teacher1','1002','contact:address','tianjian'

    put 'teacher1','1002','contact:phone','13512436987'

    在Phoenix创建映射表

    create view "teacher12"(

    "ROW1" varchar primary key,

    "contact"."address" varchar,

    "contact"."phone" varchar,

    "info"."age" varchar,

    "info"."gender" varchar,

    "info"."name" varchar

    );

    在Phoenix查找数据

    select * from "teacher";

    2.10、节点的管理

    2.10.1、服役(commissioning)

    当启动regionserver时,regionserver会向HMaster注册并开始接收本地数据,开始的时候,新加入的节点不会有任何数据,平衡器开启的情况下,将会有新的region移动到开启的RegionServer上。如果启动和停止进程是使用ssh和HBase脚本,那么会将新添加的节点的主机名加入到conf/regionservers文件中。

    1)$ ./bin/hbase-daemon.sh start regionserver

    2)hbase(main):001:0>balance_switch true

    2.10.2、退役(decommissioning)

    顾名思义,就是从当前HBase集群中删除某个RegionServer,这个过程分为如下几个过程:

    在0.90.2之前,我们只能通过在要卸载的节点上执行

    1) 停止负载平衡器

    
    hbase> balance_switch false
    
    

    2) 在退役节点上停止RegionServer

    
    [root@bigdata11 hbase-1.3.1] hbase-daemon.sh stop regionserver
    
    

    3) RegionServer一旦停止,会关闭维护的所有region

    4) Zookeeper上的该RegionServer节点消失

    5) Master节点检测到该RegionServer下线,开启平衡器

    
    hbase> balance_switch true
    
    

    6) 下线的RegionServer的region服务得到重新分配

    这种方法很大的一个缺点是该节点上的Region会离线很长时间。因为假如该RegionServer上有大量Region的话,因为Region的关闭是顺序执行的,第一个关闭的Region得等到和最后一个Region关闭并Assigned后一起上线。这是一个相当漫长的时间。每个Region Assigned需要4s,也就是说光Assigned就至少需要2个小时。该关闭方法比较传统,需要花费一定的时间,而且会造成部分region短暂的不可用。

    另一种方案:

    1. ** 新方法**

    自0.90.2之后,HBase添加了一个新的方法,即“graceful_stop”,只需要在HBase Master节点执行

    
    $ bin/graceful_stop.sh <RegionServer-hostname>
    
    

    该命令会自动关闭Load Balancer,然后Assigned Region,之后会将该节点关闭。除此之外,你还可以查看remove的过程,已经assigned了多少个Region,还剩多少个Region,每个Region 的Assigned耗时

    1. 开启负载平衡器
    hbase> balance_switch true
    
    

    相关文章

      网友评论

          本文标题:二、HBase部署与使用

          本文链接:https://www.haomeiwen.com/subject/wuolnctx.html