HBase 教程(超詳細)

1. HBase 簡介

1.1 HBase 定義

  HBase 是一種分佈式、可擴展、支持海量數據存儲的 NoSQL 數據庫。

1.2 HBase 背景

  HBase 的原型是 Google 的 BigTable 論文,受到了該論文思想的啓發,目前作爲 Hadoop的子項目來開發維護,用於支持結構化的數據存儲。

  • 2006 年 Google 發表 BigTable 白皮書
  • 2006 年開始開發 HBase
  • 2008 年北京成功開奧運會,程序員默默地將 HBase 弄成了 Hadoop 的子項目
  • 2010 年 HBase 成爲 Apache 頂級項目
  • 現在很多公司二次開發出了很多發行版本

  HBase 是一個高可靠性、高性能、面向列、可伸縮的分佈式存儲系統,利用 HBASE 技術可在廉價 PC Server 上搭建起大規模結構化存儲集羣。HBase 的目標是存儲並處理大型的數據,更具體來說是僅需使用普通的硬件配置,就能夠處理由成千上萬的行和列所組成的大型數據。

  HBase 是 Google Bigtable 的開源實現,但是也有很多不同之處。比如:

  • Google Bigtable 利用 GFS 作爲其文件存儲系統,HBase 利用 Hadoop HDFS 作爲其文件存儲系統;
  • Google 運行 MapReduce 來處理 Bigtable 中的海量數據,HBase 同樣利用 Hadoop MapReduce 來處理 HBase 中的海量數據;
  • Google Bigtable 利用 Chubby 作爲協同服務,HBase 利用 Zookeeper 作爲對應。

1.3 HBase 數據模型

  邏輯上,HBase 的數據模型同關係型數據庫很類似,數據存儲在一張表中,有行有列。但從 HBase 的底層物理存儲結構(K-V)來看,HBase 更像是一個 multi-dimensional map。

1.3.1 HBase 邏輯結構

在這裏插入圖片描述

1.3.2 HBase 物理存儲結構

在這裏插入圖片描述

1.3.3 數據模型

  1. NameSpace

    命名空間,類似於關係型數據庫的 DatabBase 概念,每個命名空間下有多個表。HBase 有兩個自帶的命名空間,分別是 hbase 和 default,hbase 中存放的是 HBase 內置的表,default 表是用戶默認使用的命名空間。

  2. Region

    類似於關係型數據庫的表概念。不同的是,HBase 定義表時只需要聲明列族即可,不需要聲明具體的列。這意味着,往 HBase 寫入數據時,字段可以動態、按需指定。因此,和關係型數據庫相比,HBase 能夠輕鬆應對字段變更的場景。

  3. Row

    HBase 表中的每行數據都由一個 RowKey 和多個 Column(列)組成,數據是按照 RowKey 的字典順序存儲的,並且查詢數據時只能根據 RowKey 進行檢索,所以 RowKey 的設計十分重要。

  4. Column

    HBase 中的每個列都由 Column Family(列族)和 Column Qualifier(列限定符)進行限
    定,例如 info:name,info:age。建表時,只需指明列族,而列限定符無需預先定義。

  5. Time Stamp

    用於標識數據的不同版本(version),每條數據寫入時,如果不指定時間戳,系統會
    自動爲其加上該字段,其值爲寫入 HBase 的時間。

  6. Cell

    由 {rowkey, column Family:column Qualifier, time Stamp} 唯一確定的單元。cell 中的數
    據是沒有類型的,全部是字節碼形式存貯。

1.4 HBase 基本架構

(不完整版)
在這裏插入圖片描述

  1. RegionServer

    Region Server 爲 Region 的管理者,其實現類爲 HRegionServer,主要作用如下:

    ① 對於數據的操作:get, put, delete;
    ② 對於 Region 的操作:splitRegion、compactRegion。

  2. Master

    Master 是所有 RegionServer 的管理者,其實現類爲 HMaster,主要作用如下:

    ① 對於表的操作:create, delete, alter
    ② 對於 RegionServer的操作:分配 regions 到每個 RegionServer,監控每個 RegionServer 的狀態,負載均衡和故障轉移。

  3. Zookeeper

    HBase 通過 Zookeeper 來做 Master 的高可用、RegionServer 的監控、元數據的入口以及
    集羣配置的維護等工作。

  4. HDFS

    HDFS 爲 HBase 提供最終的底層數據存儲服務,同時爲 HBase 提供高可用的支持。


2. HBase 快速入門

2.1 HBase 官網地址

  HBase 官網

2.2 HBase 安裝流程

  1. 啓動 Hadoop 集羣
  2. 啓動 Zookeeper
  3. 將 HBase 的安裝包上傳到服務器上(hbase-2.2.2-bin.tar.gz)
  4. 解壓 HBase 到指定目錄
tar -zxvf hbase-2.2.2-bin.tar.gz -C /hadoop/
  1. 修改 HBase 的配置文件(/hadoop/hbase-2.2.2/conf/ 目錄下)

    ① hbase-env.sh 修改內容:

# The java implementation to use.  Java 1.8+ required.
export JAVA_HOME=/usr/local/java/jdk1.8.0_151
# Tell HBase whether it should manage it's own instance of ZooKeeper or not.
export HBASE_MANAGES_ZK=false

    ② hbase-site.xml 修改內容:

<configuration>
  <property>   
    <name>hbase.rootdir</name> 
    <value>hdfs://master:9000/hbase</value>
  </property>

  <property> 
    <name>hbase.cluster.distributed</name>
    <value>true</value>
  </property>

  <!-- 0.98後的新變動,之前版本沒有.port,默認端口爲60000 -->
  <property>
    <name>hbase.master.port</name>
    <value>16000</value>
  </property>

  <property> 
    <name>hbase.zookeeper.quorum</name>
    <value>master:2181,slave1:2181,slave2:2181</value>
  </property>

  <property> 
    <name>hbase.zookeeper.property.dataDir</name>
    <value>/hadoop/zookeeper-3.5.6/zkData</value>
  </property>
</configuration>

    ③ regionservers:

master
slave1
slave2

    ⑤ 軟連接 hadoop 配置文件到 hbase:

ln -s /hadoop/hadoop-2.7.7/etc/hadoop/core-site.xml /hadoop/hbase-2.2.2/conf/core-site.xml
ln -s /hadoop/hadoop-2.7.7/etc/hadoop/hdfs-site.xml /hadoop/hbase-2.2.2/conf/hdfs-site.xml
  1. 將 HBase 同步到其他機器上
xsync /hadoop/hbase-2.2.2/
  1. 配置環境變量
vim /etc/profile

   添加以下內容:

#HBASE
export HBASE_HOME=/hadoop/hbase-2.2.2
export PATH=$PATH:$HBASE_HOME/bin

   使配置文件生效

source /etc/profile

   同步其他機器配置文件並分別使配置文件生效

xsync /etc/profile
  1. HBase 服務的啓動

    ① 方式一

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

    ② 方式二

start-hbase.sh

   對應的停止服務

stop-hbase.sh
  1. 查看 HBase 頁面

  http://master:16010
在這裏插入圖片描述

2.3 HBase Shell 操作

2.3.1 基本操作

  1. 進入 HBase 客戶端命令行
hbase shell
  1. 查看幫助命令
help
  1. 查看當前數據庫中有哪些表
list

2.3.2 表的操作

  1. 創建表
create 'student','info'
  1. 插入數據到表
put 'student','1001','info:sex','male'
put 'student','1001','info:age','18'
put 'student','1002','info:name','Janna'
put 'student','1002','info:sex','female'
put 'student','1002','info:age','20'
  1. 掃描查看錶數據
scan 'student'

在這裏插入圖片描述

scan 'student',{STARTROW => '1001', STOPROW  => '1001'}
scan 'student',{STARTROW => '1001'}
  1. 查看錶結構
describe 'student'
  1. 更新指定字段的數據
put 'student','1001','info:name','Nick'
put 'student','1001','info:age','100'
  1. 查看 “指定行” 或 “指定列族:列” 的數據
get 'student','1001'
get 'student','1001','info:name'
  1. 統計表數據行數
count 'student'
  1. 變更表信息

    將 info 列族中的數據存放 3 個版本

alter 'student',{NAME=>'info',VERSIONS=>3}
get 'student','1001',{COLUMN=>'info:name',VERSIONS=>3}
  1. 刪除數據

    ① 刪除某 rowkey 的全部數據

deleteall 'student','1001'

    ② 刪除某 rowkey 的某一列數據

delete 'student','1002','info:sex'
  1. 清空表數據
truncate 'student'

   提示:清空表的操作順序爲先 disable,然後再 truncate。

  1. 刪除表

    ① 首先需要先讓該表爲 disable 狀態

disable 'student'

    ② 然後才能 drop 這個表

drop 'student'

2.3.3 命名空間的基本操作

  1. 查看命名空間
list_namespace
  1. 創建命名空間
create_namespace 'bigdata'
  1. 在新的命名空間中創建表
create 'bigdata:student','info'
  1. 刪除命名空間

    只能刪除空的命名空間,如果不爲空,需要先刪除該命名空間下的所有表

drop_namespace 'bigdata'

3. HBase 進階

3.1 架構原理

在這裏插入圖片描述

  1. StoreFile

    保存實際數據的物理文件,StoreFile 以 HFile 的形式存儲在 HDFS 上。每個 Store 會有一個或多個 StoreFile(HFile),數據在每個 StoreFile 中都是有序的。

  2. MemStore

    寫緩存,由於 HFile 中的數據要求是有序的,所以數據是先存儲在 MemStore 中,排好序後,等到達刷寫時機纔會刷寫到 HFile,每次刷寫都會形成一個新的 HFile。

  3. WAL

    由於數據要經 MemStore 排序後才能刷寫到 HFile,但把數據保存在內存中會有很高的概率導致數據丟失,爲了解決這個問題,數據會先寫在一個叫做 Write-Ahead logfile 的文件中,然後再寫入 MemStore 中。所以在系統出現故障的時候,數據可以通過這個日誌文件重建。

3.2 讀流程

在這裏插入圖片描述

  1. Client 先訪問 zookeeper,獲取 hbase:meta 表位於哪個 Region Server。
  2. 訪問對應的 Region Server,獲取 hbase:meta 表,根據讀請求的 namespace:table/rowkey,查詢出目標數據位於哪個 Region Server 中的哪個 Region 中。並將該 table 的 region 信息以及 meta 表的位置信息緩存在客戶端的 meta cache,方便下次訪問。
  3. 與目標 Region Server 進行通訊;
  4. 將數據順序寫入(追加)到 WAL;
  5. 將數據寫入對應的 MemStore,數據會在 MemStore 進行排序;
  6. 向客戶端發送 ack;
  7. 等達到 MemStore 的刷寫時機後,將數據刷寫到 HFile。

3.3 MemStore Flush

在這裏插入圖片描述

  1. 當某個 memstroe 的大小達到了 hbase.hregion.memstore.flush.size(默認值 128M), 其所在 region 的所有 memstore 都會刷寫,並且會阻止繼續往該 memstore 寫數據。

  2. 當 region server 中 memstore 的總大小達到 *hbase.regionserver.global.memstore.size(默認值 0.4), *hbase.regionserver.global.memstore.size.lower.limit(默認值 0.95),region 會按照其所有 memstore 的大小順序(由大到小)依次進行刷寫。直到 region server 中所有 memstore 的總大小減小到上述值以下。

    當 region server 中 memstore 的總大小達到 java_heapsize*hbase.regionserver.global.memstore.size(默認值 0.4)時,會阻止繼續往所有的 memstore 寫數據。

  3. 到達自動刷寫的時間,也會觸發 memstore flush。自動刷新的時間間隔由該屬性進行配置 hbase.regionserver.optionalcacheflushinterval(默認 1 小時)

  4. 當 WAL 文件的數量超過 hbase.regionserver.max.logs,region 會按照時間順序依次進
    行刷寫,直到 WAL 文件數量減小到 hbase.regionserver.max.log 以下(該屬性名已經廢棄,
    現無需手動設置,最大值爲 32)。

3.4 讀流程

在這裏插入圖片描述

  1. Client 先訪問 zookeeper,獲取 hbase:meta 表位於哪個 Region Server。
  2. 訪問對應的 Region Server,獲取 hbase:meta 表,根據讀請求的 namespace:table/rowkey,查詢出目標數據位於哪個 Region Server 中的哪個 Region 中。並將該 table 的 region 信息以及 meta 表的位置信息緩存在客戶端的 meta cache,方便下次訪問。
  3. 與目標 Region Server 進行通訊;
  4. 分別在 Block Cache(讀緩存),MemStore 和 Store File(HFile)中查詢目標數據,並將查到的所有數據進行合併。此處所有數據是指同一條數據的不同版本(time stamp)或者不同的類型(Put/Delete)。
  5. 將從文件中查詢到的數據塊(Block,HFile 數據存儲單元,默認大小爲 64KB)緩存到 Block Cache。
  6. 將合併後的最終結果返回給客戶端。

3.5 StoreFile Compaction

  由於 memstore 每次刷寫都會生成一個新的HFile,且同一個字段的不同版本(timestamp)和不同類型(Put/Delete)有可能會分佈在不同的 HFile 中,因此查詢時需要遍歷所有的 HFile。爲了減少 HFile 的個數,以及清理掉過期和刪除的數據,會進行 StoreFile Compaction。

  Compaction 分爲兩種,分別是 Minor Compaction 和 Major Compaction。Minor Compaction 會將臨近的若干個較小的 HFile 合併成一個較大的 HFile,但不會清理過期和刪除的數據。
Major Compaction 會將一個 Store 下的所有的 HFile 合併成一個大 HFile,並且會清理掉過期和刪除的數據。
在這裏插入圖片描述

3.6 Region Split

  默認情況下,每個 Table 起初只有一個 Region,隨着數據的不斷寫入,Region 會自動進
行拆分。剛拆分時,兩個子 Region 都位於當前的 Region Server,但處於負載均衡的考慮,HMaster 有可能會將某個 Region 轉移給其他的 Region Server。

  1. 當 1 個 region 中的某個 Store 下所有 StoreFile 的總大小超過 hbase.hregion.max.filesize, 該 Region 就會進行拆分(0.94 版本之前)。
  2. 當 1 個 region 中 的 某 個 Store 下所有 StoreFile 的 總 大 小 超 過 Min(R^2 *
    “hbase.hregion.memstore.flush.size”,hbase.hregion.max.filesize"),該 Region 就會進行拆分,其
    中 R 爲當前 Region Server 中屬於該 Table 的個數(0.94 版本之後)。
    在這裏插入圖片描述

4. HBase API 操作

4.1 環境準備

  新建項目後在 pom.xml 中添加依賴:

<dependencies>
    <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-server</artifactId>
        <version>2.2.2</version>
    </dependency>

    <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-client</artifactId>
        <version>2.2.2</version>
    </dependency>
    
	<dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
</dependencies>

  在 resources 目錄下創建 log4j.properties(在控制檯打印日誌)

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

4.2 HBase API

4.2.1 Hbase 的連接與斷開

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;


import java.io.IOException;

public class TestHBase {

    static Admin admin = null;
    static Connection connection = null;

    static {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "192.168.217.130");
        // 獲取連接對象
        try {
            connection = ConnectionFactory.createConnection(conf);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            admin = connection.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void close(Connection conn, Admin admin) throws IOException {
        if (conn != null) {
            conn.close();
        }
        if (admin != null) {
            admin.close();
        }
    }
}

6.2.2 判斷表是否存在

public static boolean tableExist(String tableName) throws IOException {
    boolean tableExists = admin.tableExists(TableName.valueOf(tableName));
    return tableExists;
}

4.2.3 創建表

public static void createTable(String tableName, String... columnFamily) throws IOException {
        // 判斷是否存在列族信息
        if (columnFamily.length <= 0) {
            System.out.println("請設置列族信息!");
            return;
        }
        //判斷表是否存在
        if (tableExist(tableName)) {
            System.out.println("表" + tableName + "已存在");
        } else {
            //創建表描述器
            TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(TableName.valueOf(tableName));
            //創建多個列族
            for (String cf : columnFamily) {
                // 創建列族描述器
                ColumnFamilyDescriptor columnFamilyDescriptor = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("data")).build();
                tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptor);
            }
            //根據對錶的配置,創建表
            admin.createTable(tableDescriptorBuilder.build());
            System.out.println("表" + tableName + "創建成功!");
        }
    }

4.2.4 刪除表

public static void deleteTable(String tableName) throws IOException {
    if (tableExist(tableName)) {
        // 使表不可用
        admin.disableTable(TableName.valueOf(tableName));
        // 執行刪除操作
        admin.deleteTable(TableName.valueOf(tableName));
        System.out.println("表" + tableName + "刪除成功!");
    } else {
        System.out.println("表" + tableName + "不存在!");
    }
}

4.2.5 創建命名空間

public static void createNameSpace(String nameSpace) {
    NamespaceDescriptor namespaceDescriptor = NamespaceDescriptor.create(nameSpace).build();
    try {
        admin.createNamespace(namespaceDescriptor);
    } catch (NamespaceExistException e) {
        System.out.println(nameSpace + "命名空間已經存在!");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

4.2.6 向表中插入數據

public static void addRowData(String tableName, String rowKey, String columnFamily, String column, String value) throws IOException {
    // 獲取Table對象
    Table table = connection.getTable(TableName.valueOf(tableName));
    //向表中插入數據
    Put put = new Put(Bytes.toBytes(rowKey));
    //向Put對象中組裝數據
    put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value));
    table.put(put);
    table.close();
    System.out.println("插入數據成功");
}

4.2.7 刪除多行數據

public static void deleteData(String tableName, String... rowKey) throws IOException {
    Table table = connection.getTable(TableName.valueOf(tableName));
    List<Delete> deleteList = new ArrayList<Delete>();
    for (String row : rowKey) {
        Delete delete = new Delete(Bytes.toBytes(row));
        deleteList.add(delete);
    }
    table.delete(deleteList);
    table.close();
}

4.2.8 全表掃描

public static void scanTable(String tableName) throws IOException {
    Table table = connection.getTable(TableName.valueOf(tableName));
    //得到用於掃描region的對象
    Scan scan = new Scan();
    //使用table得到resultcanner實現類的對象
    ResultScanner results = table.getScanner(scan);
    for (Result result : results) {
        Cell[] cells = result.rawCells();
        for (Cell cell : cells) {
            //得到rowkey
            System.out.println("行鍵:" + Bytes.toString(CellUtil.cloneRow(cell)) +
                    ",列族" + Bytes.toString(CellUtil.cloneFamily(cell)) +
                    ",列:" + Bytes.toString(CellUtil.cloneQualifier(cell)) +
                    ",值:" + Bytes.toString(CellUtil.cloneValue(cell)));
        }
    }
    table.close();
}

4.2.9 獲取指定 rowKey 的數據

public static void getData(String tableName, String rowKey) throws IOException {
    Table table = connection.getTable(TableName.valueOf(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(CellUtil.cloneRow(cell)) +
                ",列族" + Bytes.toString(CellUtil.cloneFamily(cell)) +
                ",列:" + Bytes.toString(CellUtil.cloneQualifier(cell)) +
                ",值:" + Bytes.toString(CellUtil.cloneValue(cell)));
    }
    table.close();
}

4.2.10 獲取指定“列族:列”的數據

public static void getData(String tableName, String rowKey, String columnFamily, String column) throws IOException {
    Table table = connection.getTable(TableName.valueOf(tableName));
    Get get = new Get(Bytes.toBytes(rowKey));
    get.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column));
    Result result = table.get(get);
    for (Cell cell : result.rawCells()) {
        System.out.println("行鍵:" + Bytes.toString(CellUtil.cloneRow(cell)) +
                ",列族" + Bytes.toString(CellUtil.cloneFamily(cell)) +
                ",列:" + Bytes.toString(CellUtil.cloneQualifier(cell)) +
                ",值:" + Bytes.toString(CellUtil.cloneValue(cell)));
    }
}

4.3 MapReduce

  通過 HBase 的相關JavaAPI,我們可以實現伴隨 HBase 操作的 MapReduce 過程,比如使用 MapReduce 將數據從本地文件系統導入到 HBase 的表中,比如我們從 HBase 中讀取一些原始數據後使用 MapReduce 做數據分析。

4.3.1 官方 HBase-MapReduce

  1. 查看 HBase 的 MapReduce 任務的執行
hbase mapredcp
  1. 環境變量的導入

    ① 執行環境變量的導入(臨時生效,在命令行執行下述操作)

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

   說明:前提已經配置了 HBASE_HOME 和 HADOOP_HOME 環境變量

    ② 永久生效:修改 hadoop-env.sh 中配置

export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:/hadoop/hbase-2.2.2/lib/*

在這裏插入圖片描述

  1. 運行官方的 MapReduce 任務

  (一)統計 Student 表中有多少行數據

yarn jar /hadoop/hbase-2.2.2/lib/hbase-mapreduce-2.2.2.jar rowcounter student

  (二)使用 MapReduce 將本地數據導入到 HBase

     ① 在本地創建一個 tsv 格式的文件:fruit.tsv

1001	Apple	Red
1002	Pear	Yellow
1003	Pineapple	Yellow

     ② 創建 HBase 表

create 'fruit','info'

     ③ 在 HDFS 中創建 input_fruit 文件夾並上傳 fruit.tsv 文件

hadoop fs -mkdir /input_fruit/
hadoop fs -put data/fruit.tsv /input_fruit/

     ④ 執行 MapReduce 到 HBase 的 fruit 表中

yarn jar /hadoop/hbase-2.2.2/lib/hbase-mapreduce-2.2.2.jar importtsv \
-Dimporttsv.columns=HBASE_ROW_KEY,info:name,info:color fruit \
hdfs://master:9000/input_fruit

     ⑤ 使用 scan 命令查看導入後的結果

scan 'fruit'

在這裏插入圖片描述

4.3.2 自定義 HBase-MapReduce1

  目標:實現將 HDFS 中的數據寫入到 Hbase 表中。
  任務:讀取 HDFS 上的 fruit.tsv,將數據寫到 HBase 中 fruit1 表。

  1. 編寫 FruitMapper 類
package mr;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class FruitMapper extends Mapper<LongWritable, Text, LongWritable, Text> {

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        context.write(key, value);
    }
}
  1. 編寫 FruitReducer 類
package mr;

import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;

import java.io.IOException;

public class FruitReducer extends TableReducer<LongWritable, Text, NullWritable> {
    @Override
    protected void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        for (Text value : values) {
            // 獲取一行數據
            String[] fields = value.toString().split("\t");
            // 構建Put對象
            Put put = new Put(Bytes.toBytes(fields[0]));
            // 給Put對象賦值
            put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes(fields[1]));
            put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("color"), Bytes.toBytes(fields[2]));
            // 寫出
            context.write(NullWritable.get(), put);
        }
    }
}
  1. 編寫 FruitDriver 類
package mr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class FruitDriver implements Tool {

    private Configuration configuration = new Configuration();

    @Override
    public int run(String[] args) throws Exception {
        // 1.獲取job對象
        Job job = Job.getInstance(configuration);
        // 2.設置驅動類路徑
        job.setJarByClass(FruitDriver.class);
        // 3.設置Mapper類和輸入輸出類型
        job.setMapperClass(FruitMapper.class);
        job.setMapOutputKeyClass(LongWritable.class);
        job.setMapOutputValueClass(Text.class);
        job.setReducerClass(FruitReducer.class);

        // 4.設置Reducer類型
        TableMapReduceUtil.initTableReducerJob(args[1], FruitReducer.class, job);

        // 設置輸入參數
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        boolean result = job.waitForCompletion(true);
        return result ? 0 : 1;
    }

    @Override
    public void setConf(Configuration conf) {

    }

    @Override
    public Configuration getConf() {
        return null;
    }

    public static void main(String[] args) throws Exception {

        Configuration configuration = new Configuration();
        int run = ToolRunner.run(configuration, new FruitDriver(), args);

    }
}
  1. 打包程序並上傳到集羣(hbase-1.0-SNAPSHOT.jar)
  2. 創建 fruit1 表
create 'fruit1','info'
  1. 運行程序
yarn jar hbase-1.0-SNAPSHOT.jar mr.FruitDriver /input_fruit/fruit.tsv fruit1
  1. 查看結果
scan 'fruit1'

4.3.3 自定義 HBase-MapReduce2

  目標:將 fruit 表中的一部分數據,通過 MR 遷入到 fruit2 表中。

  1. 編寫 Fruit2Mapper 類
package mr2;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

public class Fruit2Mapper extends TableMapper<ImmutableBytesWritable, Put> {

    @Override
    protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException {

        Put put = new Put(key.get());

        // 1.獲取數據
        for (Cell cell : value.rawCells()) {
            // 2.判斷當前cell是否爲name列
            if ("name".equals(Bytes.toString(CellUtil.cloneQualifier(cell)))) {
                // 3.給put對象賦值
                put.add(cell);
            }
        }

        // 4.寫出
        context.write(key, put);
    }
}
  1. 編寫 Fruit2Reducer 類
package mr2;

import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.io.NullWritable;

import java.io.IOException;

public class Fruit2Reducer extends TableReducer<ImmutableBytesWritable, Put, NullWritable> {

    @Override
    protected void reduce(ImmutableBytesWritable key, Iterable<Put> values, Context context) throws IOException, InterruptedException {

        for (Put put : values) {
            context.write(NullWritable.get(),put);
        }
    }
}
  1. 編寫 FruitDriver 類
package mr2;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class Fruit2Driver implements Tool {

    private Configuration configuration = null;

    @Override
    public int run(String[] args) throws Exception {
        // 1.獲取job對象
        Job job = Job.getInstance(configuration);
        // 2.設置驅動類路徑
        job.setJarByClass(Fruit2Driver.class);
        // 3.設置Mapper類和輸入輸出類型
        TableMapReduceUtil.initTableMapperJob("fruit", new Scan(), Fruit2Mapper.class, ImmutableBytesWritable.class, Put.class, job);
        // 4.設置Reducer類和輸入輸出類型
        TableMapReduceUtil.initTableReducerJob("fruit2", Fruit2Reducer.class, job);
        // 5.提交任務
        boolean result = job.waitForCompletion(true);
        return result ? 0 : 1;
    }

    @Override
    public void setConf(Configuration conf) {
        configuration = conf;
    }

    @Override
    public Configuration getConf() {
        return null;
    }

    public static void main(String[] args) throws Exception {
//        Configuration conf = new Configuration();
        Configuration conf = HBaseConfiguration.create();
        ToolRunner.run(conf,new Fruit2Driver(),args);
    }
}
  1. 將集羣中 hbase-site.xml 拷貝到項目 resource 目錄下
  2. 創建 fruit2 表
create 'fruit2','info'
  1. 運行程序
  2. 查看結果
scan 'fruit2'

4.4 與 Hive 集成

4.4.1 HBase 與 Hive 對比

  1. Hive

    數據倉庫

      Hive 的本質其實就相當於將 HDFS 中已經存儲的文件在 Mysql 中做了一個雙射關係,以方便使用 HQL 去管理查詢。

    用於數據分析、清洗

      Hive 適用於離線的數據分析和清洗,延遲較高。

    基於 HDFS、MapReduce

      Hive 存儲的數據依舊在 DataNode 上,編寫的 HQL 語句終將是轉換爲 MapReduce 代碼執行。

  2. HBase

    數據庫

      是一種面向列族存儲的非關係型數據庫。

    用於存儲結構化和非結構化的數據

      適用於單表非關係型數據的存儲,不適合做關聯查詢,類似 JOIN 等操作。

    基於 HDFS
      數據持久化存儲的體現形式是 HFile,存放於 DataNode 中,被 ResionServer 以 region 的形式進行管理。

    延遲較低,接入在線業務使用

      面對大量的企業數據,HBase 可以直線單表大量數據的存儲,同時提供了高效的數據訪問速度。

4.4.2 HBase 與 Hive 集成使用

環境準備

因爲後續會在操作 Hive 的同時對 HBase 也會產生影響,所以 Hive 需要持有操作 HBase 的 Jar,那麼接下來拷貝 Hive 所依賴的 Jar 包(或者使用軟連接的形式)。

ln -s $HBASE_HOME/lib/hbase-common-2.2.2.jar $HIVE_HOME/lib/hbase-common-2.2.2.jar
ln -s $HBASE_HOME/lib/hbase-server-2.2.2.jar $HIVE_HOME/lib/hbaseserver-2.2.2.jar
ln -s $HBASE_HOME/lib/hbase-client-2.2.2.jar $HIVE_HOME/lib/hbase-client-2.2.2.jar
ln -s $HBASE_HOME/lib/hbase-protocol-2.2.2.jar $HIVE_HOME/lib/hbase-protocol-2.2.2.jar
ln -s $HBASE_HOME/lib/hbase-it-2.2.2.jar $HIVE_HOME/lib/hbase-it-2.2.2.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-2.2.2.jar $HIVE_HOME/lib/hbase-hadoop2-compat-2.2.2.jar
ln -s $HBASE_HOME/lib/hbase-hadoop-compat-2.2.2.jar $HIVE_HOME/lib/hbase-hadoop-compat-2.2.2.jar

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

<property>
 <name>hive.zookeeper.quorum</name>
 <value>master,slave1,slave2</value>
</property>

<property>
 <name>hive.zookeeper.client.port</name>
 <value>2181</value>
</property>

案例一

   目標: 建立 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:co
mm,info:deptno")
TBLPROPERTIES ("hbase.table.name" = "hbase_emp_table");
  1. 通過 insert 命令將 emp 表中的數據導入到 Hive 關聯 Hbase 的那張表中
insert into table hive_hbase_emp_table select * from emp;
  1. 查看 Hive 以及關聯的 HBase 表中是否已經成功的同步插入了數據

    Hive:

select * from hive_hbase_emp_table;

    HBase:

scan ‘hbase_emp_table’

案例二

  目標: 在 HBase 中已經存儲了某一張表 hbase_emp_table,然後在 Hive 中創建一個外部表來關聯 HBase 中的 hbase_emp_table 這張表,使之可以藉助 Hive 來分析 HBase 這張表中的數據。

  1. 在 Hive 中創建外部表
CREATE EXTERNAL TABLE relevance_hbase_emp(
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");
  1. 查看數據
select * from relevance_hbase_emp;

5. HBase 優化

5.1 高可用

  在 HBase 中 HMaster 負責監控 HRegionServer 的生命週期,均衡 RegionServer 的負載,如果 HMaster 掛掉了,那麼整個 HBase 集羣將陷入不健康的狀態,並且此時的工作狀態並不會維持太久。所以 HBase 支持對 HMaster 的高可用配置。

  1. 關閉 HBase 集羣
stop-hbase.sh
  1. 在 conf 目錄下創建 backup-masters 文件,配置高可用 HMaster 節點
touch backup-masters
echo slave1 > backup-masters
  1. 同步配置
xsync backup-masters
  1. 啓動 HBase
start-hbase.sh

5.2 預分區

  每一個 region 維護着 StartRow 與 EndRow,如果加入的數據符合某個 Region 維護的 RowKey 範圍,則該數據交給這個 Region 維護。那麼依照這個原則,我們可以將數據所要投放的分區提前大致的規劃好,以提高 HBase 性能。

  1. 手動設定預分區
create 'staff1','info','partition1',SPLITS => ['1000','2000','3000','4000']
  1. 生成 16 進制序列預分區
create 'staff2','info','partition2',{NUMREGIONS => 15, SPLITALGO => 'HexStringSplit'}
  1. 按照文件中設置的規則預分區

    創建 splits.txt 文件內容如下:

aaaa
bbbb
cccc
dddd

    然後執行:

create 'staff3','partition3',SPLITS_FILE => 'splits.txt'

5.3 RowKey 設計

  一條數據的唯一標識就是 RowKey,那麼這條數據存儲於哪個分區,取決於 RowKey 處於哪個一個預分區的區間內,設計 RowKey 的主要目的 ,就是讓數據均勻的分佈於所有的 region 中,在一定程度上防止數據傾斜。(散列性、唯一性、長度原則)

  1. 生成隨機數、hash、散列值
  2. 字符串反轉
20170524000001 轉成 10000042507102
20170524000002 轉成 20000042507102
  1. 字符串拼接
20170524000001_a12e
20170524000001_93i7

5.4 內存優化

  HBase 操作過程中需要大量的內存開銷,畢竟 Table 是可以緩存在內存中的,一般會分配整個可用內存的 70%給 HBase 的 Java 堆。但是不建議分配非常大的堆內存,因爲 GC 過程持續太久會導致 RegionServer 處於長期不可用狀態,一般 16~48G 內存就可以了,如果因爲框架佔用內存過高導致系統內存不足,框架一樣會被系統服務拖死。

5.5 基礎優化

  1. 允許在 HDFS 的文件中追加內容

    hdfs-site.xml、hbase-site.xml
    屬性: dfs.support.append
    解釋: 開啓 HDFS 追加同步,可以優秀的配合 HBase 的數據同步和持久化。默認值爲 true。

  2. 優化 DataNode 允許的最大文件打開數

    hdfs-site.xml
    屬性: dfs.datanode.max.transfer.threads
    解釋: HBase 一般都會同一時間操作大量的文件,根據集羣的數量和規模以及數據動作,設置爲 4096 或者更高。默認值:4096

  3. 優化延遲高的數據操作的等待時間

    hdfs-site.xml
    屬性: dfs.image.transfer.timeout
    解釋: 如果對於某一次數據操作來講,延遲非常高,socket 需要等待更長的時間,建議把
    該值設置爲更大的值(默認 60000 毫秒),以確保 socket 不會被 timeout 掉。

  4. 優化數據的寫入效率

    mapred-site.xml
    屬性: mapreduce.map.output.compress、mapreduce.map.output.compress.codec
    解釋: 開啓這兩個數據可以大大提高文件的寫入效率,減少寫入時間。第一個屬性值修改爲 true,第二個屬性值修改爲:org.apache.hadoop.io.compress.GzipCodec 或者其他壓縮方式。

  5. 設置 RPC 監聽數量

    hbase-site.xml
    屬性: Hbase.regionserver.handler.count
    解釋: 默認值爲 30,用於指定 RPC 監聽的數量,可以根據客戶端的請求數進行調整,讀寫請求較多時,增加此值。

  6. 優化 HStore 文件大小

    hbase-site.xml
    屬性: hbase.hregion.max.filesize
    解釋: 默認值 10737418240(10GB),如果需要運行 HBase 的 MR 任務,可以減小此值,因爲一個 region 對應一個 map 任務,如果單個 region 過大,會導致 map 任務執行時間過長。該值的意思就是,如果 HFile 的大小達到這個數值,則這個 region 會被切分爲兩個 Hfile。

  7. 優化 HBase 客戶端緩存

    hbase-site.xml
    屬性: hbase.client.write.buffer
    解釋: 用於指定 Hbase 客戶端緩存,增大該值可以減少 RPC 調用次數,但是會消耗更多內存,反之則反之。一般我們需要設定一定的緩存大小,以達到減少 RPC 次數的目的。

  8. 指定 scan.next 掃描 HBase 所獲取的行數

    hbase-site.xml
    屬性: hbase.client.scanner.caching
    解釋: 用於指定 scan.next 方法獲取的默認行數,值越大,消耗內存越大。

  9. flush、compact、split 機制

    當 MemStore 達到閾值,將 Memstore 中的數據 Flush 進 Storefile;
    compact 機制則是把 flush出來的小文件合併成大的 Storefile 文件;
    split 則是當 Region 達到閾值,會把過大的 Region一分爲二。

    涉及屬性:

hbase.hregion.memstore.flush.size:134217728

即:這個參數的作用是當單個 HRegion 內所有的 Memstore 大小總和超過指定值時,flush 該 HRegion 的所有 memstore。RegionServer 的 flush 是通過將請求添加一個隊列,模擬生產消費模型來異步處理的。那這裏就有一個問題,當隊列來不及消費,產生大量積壓請求時,可能會導致內存陡增,最壞的情況是觸發 OOM。

hbase.regionserver.global.memstore.upperLimit:0.4
hbase.regionserver.global.memstore.lowerLimit:0.38

即:當 MemStore 使用內存總量達到 hbase.regionserver.global.memstore.upperLimit 指定值時,將會有多個 MemStores flush 到文件中,MemStore flush 順序是按照大小降序執行的,直到刷新到 MemStore 使用內存略小於 lowerLimit。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章