HBase的安裝和使用

文章作者:foochane

原文鏈接:https://foochane.cn/article/2019062801.html

1 Hbase基本介紹

Hbase是一個分布式數(shù)據(jù)庫,可以提供數(shù)據(jù)的實時隨機讀寫。

Hbasemysql、oralce、db2、sqlserver等關(guān)系型數(shù)據(jù)庫不同,它是一個NoSQL數(shù)據(jù)庫(非關(guān)系型數(shù)據(jù)庫),并且有如下特點:

  • Hbase的表模型與關(guān)系型數(shù)據(jù)庫的表模型不同:
  • Hbase的表沒有固定的字段定義;
  • Hbase的表中每行存儲的都是一些key-value
  • Hbase的表中有列族的劃分,用戶可以指定將哪些kv插入哪個列族
  • Hbase的表在物理存儲上,是按照列族來分割的,不同列族的數(shù)據(jù)一定存儲在不同的文件中
  • Hbase的表中的每一行都固定有一個行鍵,而且每一行的行鍵在表中不能重復(fù)
  • Hbase中的數(shù)據(jù),包含行鍵,包含key,包含value,都是byte[ ]類型,hbase不負(fù)責(zé)為用戶維護數(shù)據(jù)類型
  • Hbase對事務(wù)的支持很差

HBASE相比于其他nosql數(shù)據(jù)庫(mongodbredis、cassendrahazelcast)的特點:
因為Hbase的表數(shù)據(jù)存儲在HDFS文件系統(tǒng)中,所以存儲容量可以線性擴展; 數(shù)據(jù)存儲的安全性可靠性極高!

2 Hbase的表結(jié)構(gòu)

rowkey:行鍵 base_info extra_info
001 name:zs,age:22,sex:male hobbiy:read,addr:beijing
002 name:laowang,sex:male

hbase的表模型跟mysql之類的關(guān)系型數(shù)據(jù)庫的表模型差別巨大

hbase的表模型中有:行的概念;但沒有字段的概念

行中存的都是key-value對,每行中的key-value對中的key可以是各種各樣的。

hbase表模型的要點

  • 一個表,有表名
  • 一個表可以分為多個列族(不同列族的數(shù)據(jù)會存儲在不同文件中)
  • 表中的每一行有一個“行鍵rowkey”,而且行鍵在表中不能重復(fù)
  • 表中的每一對key-value叫做一個cell
  • hbase可以對數(shù)據(jù)存儲多個歷史版本(歷史版本數(shù)量可配置),默認(rèn)取最新的版本
  • 整張表由于數(shù)據(jù)量過大,會被橫向切分成若干個region(用rowkey范圍標(biāo)識),不同region的數(shù)據(jù)也存儲在不同文件中

hbase會對插入的數(shù)據(jù)按順序存儲:

  • 首先會按行鍵排序
  • 同一行里面的kv會按列族排序,再按k排序

hbase的表數(shù)據(jù)類型:

hbase中只支持byte[] ,此處的byte[] 包括了: rowkey,key,value,列族名,表名。
表劃分為不同的region。

3 Hbase工作機制

[圖片上傳失敗...(image-ec30fc-1561887883664)]

Hbase分布式系統(tǒng)包含兩個角色

  • 管理角色:HMaster(一般2臺,一臺active,一臺standby)
  • 數(shù)據(jù)節(jié)點角色:HRegionServer(多臺,和datanode在一起)

Hbase不做數(shù)據(jù)處理的話,不需要yarn,yarn是復(fù)制Mapreduce計算的,Hbase只是負(fù)責(zé)數(shù)據(jù)管理

4 Hbase安裝

4.1 安裝準(zhǔn)備

首先,要有一個HDFS集群,并正常運行; Hbaseregionserver應(yīng)該跟hdfs中的datanode在一起
其次,還需要一個zookeeper集群,并正常運行,所以安裝Hbase要先安裝zookeeper,zookeeper前面已經(jīng)安裝過了。
然后,安裝Hbase

4.2 節(jié)點安排

各個節(jié)點角色分配如下:

節(jié)點 安裝的服務(wù)
Master namenode datanode regionserver hmaster zookeeper
Slave01 datanode regionserver zookeeper
Slave02 datanode regionserver zookeeper

4.3 安裝Hbase

解壓hbase安裝包 hbase-2.0.5-bin.tar.gz

修改hbase-env.sh

export JAVA_HOME=/usr/local/bigdata/java/jdk1.8.0_211

# 不啟動hbase自帶的zookeeper,我們自己已經(jīng)裝了
export HBASE_MANAGES_ZK=false

修改hbase-site.xml

<configuration>
    <!-- 指定hbase在HDFS上存儲的路徑 -->
    <property>
        <name>hbase.rootdir</name>
        <value>hdfs://Master:9000/hbase</value>
    </property>
    <!-- 指定hbase是分布式的 -->
    <property>
        <name>hbase.cluster.distributed</name>
        <value>true</value>
    </property>
    <!-- 指定zk的地址,多個用“,”分割 -->
    <property>
        <name>hbase.zookeeper.quorum</name>
        <value>Master:2181,Slave01:2181,Slave02:2181</value>
    </property>
</configuration>

修改 regionservers

Master
Slave01
Slave02

修改完成后,將安裝文件夾放到三個節(jié)點的/usr/local/bigdata/目錄下

6 啟動Hbase集群

先檢查hdfszookeeper是否正常啟動,
Master:

hadoop@Master:~$ jps
4918 DataNode
2744 QuorumPeerMain
4748 NameNode
9949 Jps
5167 SecondaryNameNode
hadoop@Master:~$ /usr/local/bigdata/zookeeper-3.4.6/bin/zkServer.sh status
JMX enabled by default
Using config: /usr/local/bigdata/zookeeper-3.4.6/bin/../conf/zoo.cfg
Mode: follower

Slave01:

hadoop@Slave1:~$ jps
3235 QuorumPeerMain
3779 DataNode
5546 Jps
hadoop@Slave1:~$  /usr/local/bigdata/zookeeper-3.4.6/bin/zkServer.sh status
JMX enabled by default
Using config: /usr/local/bigdata/zookeeper-3.4.6/bin/../conf/zoo.cfg
Mode: leader

Slave02:

hadoop@Slave2:~$ jps
11958 DataNode
13656 Jps
11390 QuorumPeerMain
hadoop@Slave2:~$  /usr/local/bigdata/zookeeper-3.4.6/bin/zkServer.sh status
JMX enabled by default
Using config: /usr/local/bigdata/zookeeper-3.4.6/bin/../conf/zoo.cfg
Mode: follower

然后執(zhí)行start-hbase.sh

$ bin/start-hbase.sh

上面的命令會啟動配置文件regionserver里添加的所有機器,如果想手動啟動其中一臺可以用:

$ bin/hbase-daemon.sh start regionserver

啟動完成后在Master上會啟動HRegionServerHMaster兩個服務(wù),Slave01Slave02會啟動HMaster服務(wù)。

高可用Hbase集群應(yīng)配置兩臺master一臺處于active狀態(tài)一臺處于standby狀態(tài),用于監(jiān)聽regionserver

可以再從另外兩條機器中再啟動一個HRegionServer服務(wù)。

$ bin/hbase-daemon.sh start master

新啟的這個master會處于backup狀態(tài)

7 啟動Hbase的命令行客戶端

使用命令hbase shell

bin/hbase shell
Hbase> list     // 查看表
Hbase> status   // 查看集群狀態(tài)
Hbase> version  // 查看集群版本
問題
ERROR: org.apache.hadoop.hbase.ipc.ServerNotRunningYetException: Server is not running yet
        at org.apache.hadoop.hbase.master.HMaster.checkServiceStarted(HMaster.java:2932)
        at org.apache.hadoop.hbase.master.MasterRpcServices.isMasterRunning(MasterRpcServices.java:1084)
        at org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos$MasterService$2.callBlockingMethod(MasterProtos.java)
        at org.apache.hadoop.hbase.ipc.RpcServer.call(RpcServer.java:413)
        at org.apache.hadoop.hbase.ipc.CallRunner.run(CallRunner.java:130)
        at org.apache.hadoop.hbase.ipc.RpcExecutor$Handler.run(RpcExecutor.java:324)
        at org.apache.hadoop.hbase.ipc.RpcExecutor$Handler.run(RpcExecutor.java:304)

解決
$ hdfs dfsadmin -safemode leave

8 Hbase命令行客戶端操作

8.1 建表

create 't_user_info','base_info','extra_info'
         表名      列族名   列族名
         

8.2 插入數(shù)據(jù):

hbase(main):011:0> put 't_user_info','001','base_info:username','zhangsan'
0 row(s) in 0.2420 seconds

hbase(main):012:0> put 't_user_info','001','base_info:age','18'
0 row(s) in 0.0140 seconds

hbase(main):013:0> put 't_user_info','001','base_info:sex','female'
0 row(s) in 0.0070 seconds

hbase(main):014:0> put 't_user_info','001','extra_info:career','it'
0 row(s) in 0.0090 seconds

hbase(main):015:0> put 't_user_info','002','extra_info:career','actoress'
0 row(s) in 0.0090 seconds

hbase(main):016:0> put 't_user_info','002','base_info:username','liuyifei'
0 row(s) in 0.0060 seconds

8.3 查詢數(shù)據(jù)方式一:scan 掃描

hbase(main):017:0> scan 't_user_info'
ROW                               COLUMN+CELL                                                                                     
 001                              column=base_info:age, timestamp=1496567924507, value=18                                         
 001                              column=base_info:sex, timestamp=1496567934669, value=female                                     
 001                              column=base_info:username, timestamp=1496567889554, value=zhangsan                              
 001                              column=extra_info:career, timestamp=1496567963992, value=it                                     
 002                              column=base_info:username, timestamp=1496568034187, value=liuyifei                              
 002                              column=extra_info:career, timestamp=1496568008631, value=actoress                               
2 row(s) in 0.0420 seconds

8.4 查詢數(shù)據(jù)方式二:get 單行數(shù)據(jù)

hbase(main):020:0> get 't_user_info','001'
COLUMN                            CELL                                                                                            
 base_info:age                    timestamp=1496568160192, value=19                                                               
 base_info:sex                    timestamp=1496567934669, value=female                                                           
 base_info:username               timestamp=1496567889554, value=zhangsan                                                         
 extra_info:career                timestamp=1496567963992, value=it                                                               
4 row(s) in 0.0770 seconds

8.5 刪除一個kv數(shù)據(jù)

hbase(main):021:0> delete 't_user_info','001','base_info:sex'
0 row(s) in 0.0390 seconds

刪除整行數(shù)據(jù):
hbase(main):024:0> deleteall 't_user_info','001'
0 row(s) in 0.0090 seconds

hbase(main):025:0> get 't_user_info','001'
COLUMN                            CELL                                                                                            
0 row(s) in 0.0110 seconds

3.4.1.6.    刪除整個表:
hbase(main):028:0> disable 't_user_info'
0 row(s) in 2.3640 seconds

hbase(main):029:0> drop 't_user_info'
0 row(s) in 1.2950 seconds

hbase(main):030:0> list
TABLE                                                                                                                             
0 row(s) in 0.0130 seconds

=> []

8.6 Hbase重要特性--排序特性(行鍵)

插入到hbase中去的數(shù)據(jù),hbase會自動排序存儲:
排序規(guī)則: 首先看行鍵,然后看列族名,然后看列(key)名; 按字典順序

Hbase的這個特性跟查詢效率有極大的關(guān)系

比如:一張用來存儲用戶信息的表,有名字,戶籍,年齡,職業(yè)....等信息
然后,在業(yè)務(wù)系統(tǒng)中經(jīng)常需要:
查詢某個省的所有用戶
經(jīng)常需要查詢某個省的指定姓的所有用戶

思路:如果能將相同省的用戶在hbase的存儲文件中連續(xù)存儲,并且能將相同省中相同姓的用戶連續(xù)存儲,那么,上述兩個查詢需求的效率就會提高?。。?/p>

做法:將查詢條件拼到rowkey內(nèi)

9 HBASE客戶端API操作

9.1 DDL操作

代碼流程:

  • 創(chuàng)建一個連接:Connection conn = ConnectionFactory.createConnection(conf);
  • 拿到一個DDL操作器:表管理器:adminAdmin admin = conn.getAdmin();
  • 用表管理器的api去建表、刪表、修改表定義:admin.createTable(HTableDescriptor descriptor);
@Before
public void getConn() throws Exception{
    // 構(gòu)建一個連接對象
    Configuration conf = HBaseConfiguration.create(); // 會自動加載hbase-site.xml
    conf.set("hbase.zookeeper.quorum", "192.168.233.200:2181,192.168.233.201:2181,192.168.233.202:2181");
    
    conn = ConnectionFactory.createConnection(conf);
}


/**
 * DDL
 * @throws Exception 
 */
@Test
public void testCreateTable() throws Exception{

    // 從連接中構(gòu)造一個DDL操作器
    Admin admin = conn.getAdmin();
    
    // 創(chuàng)建一個表定義描述對象
    HTableDescriptor hTableDescriptor = new HTableDescriptor(TableName.valueOf("user_info"));
    
    // 創(chuàng)建列族定義描述對象
    HColumnDescriptor hColumnDescriptor_1 = new HColumnDescriptor("base_info");
    hColumnDescriptor_1.setMaxVersions(3); // 設(shè)置該列族中存儲數(shù)據(jù)的最大版本數(shù),默認(rèn)是1
    
    HColumnDescriptor hColumnDescriptor_2 = new HColumnDescriptor("extra_info");
    
    // 將列族定義信息對象放入表定義對象中
    hTableDescriptor.addFamily(hColumnDescriptor_1);
    hTableDescriptor.addFamily(hColumnDescriptor_2);
    
    
    // 用ddl操作器對象:admin 來建表
    admin.createTable(hTableDescriptor);
    
    // 關(guān)閉連接
    admin.close();
    conn.close();
    
}


/**
 * 刪除表
 * @throws Exception 
 */
@Test
public void testDropTable() throws Exception{
    
    Admin admin = conn.getAdmin();
    
    // 停用表
    admin.disableTable(TableName.valueOf("user_info"));
    // 刪除表
    admin.deleteTable(TableName.valueOf("user_info"));
    
    
    admin.close();
    conn.close();
}

// 修改表定義--添加一個列族
@Test
public void testAlterTable() throws Exception{
    
    Admin admin = conn.getAdmin();
    
    // 取出舊的表定義信息
    HTableDescriptor tableDescriptor = admin.getTableDescriptor(TableName.valueOf("user_info"));
    
    
    // 新構(gòu)造一個列族定義
    HColumnDescriptor hColumnDescriptor = new HColumnDescriptor("other_info");
    hColumnDescriptor.setBloomFilterType(BloomType.ROWCOL); // 設(shè)置該列族的布隆過濾器類型
    
    // 將列族定義添加到表定義對象中
    tableDescriptor.addFamily(hColumnDescriptor);
    
    
    // 將修改過的表定義交給admin去提交
    admin.modifyTable(TableName.valueOf("user_info"), tableDescriptor);
    
    
    admin.close();
    conn.close();
    
}

9.2 DML操作

HBase的增刪改查

    Connection conn = null;
    
    @Before
    public void getConn() throws Exception{
        // 構(gòu)建一個連接對象
        Configuration conf = HBaseConfiguration.create(); // 會自動加載hbase-site.xml
        conf.set("hbase.zookeeper.quorum", "Master:2181,Slave01:2181,Slave02:2181");
        
        conn = ConnectionFactory.createConnection(conf);
    }
    
    
    /**
     * 增
     * 改:put來覆蓋
     * @throws Exception 
     */
    @Test
    public void testPut() throws Exception{
        
        // 獲取一個操作指定表的table對象,進行DML操作
        Table table = conn.getTable(TableName.valueOf("user_info"));
        
        // 構(gòu)造要插入的數(shù)據(jù)為一個Put類型(一個put對象只能對應(yīng)一個rowkey)的對象
        Put put = new Put(Bytes.toBytes("001"));
        put.addColumn(Bytes.toBytes("base_info"), Bytes.toBytes("username"), Bytes.toBytes("張三"));
        put.addColumn(Bytes.toBytes("base_info"), Bytes.toBytes("age"), Bytes.toBytes("18"));
        put.addColumn(Bytes.toBytes("extra_info"), Bytes.toBytes("addr"), Bytes.toBytes("北京"));
        
        
        Put put2 = new Put(Bytes.toBytes("002"));
        put2.addColumn(Bytes.toBytes("base_info"), Bytes.toBytes("username"), Bytes.toBytes("李四"));
        put2.addColumn(Bytes.toBytes("base_info"), Bytes.toBytes("age"), Bytes.toBytes("28"));
        put2.addColumn(Bytes.toBytes("extra_info"), Bytes.toBytes("addr"), Bytes.toBytes("上海"));
    
        
        ArrayList<Put> puts = new ArrayList<>();
        puts.add(put);
        puts.add(put2);
        
        
        // 插進去
        table.put(puts);
        
        table.close();
        conn.close();
        
    }
    
    
    /**
     * 循環(huán)插入大量數(shù)據(jù)
     * @throws Exception 
     */
    @Test
    public void testManyPuts() throws Exception{
        
        Table table = conn.getTable(TableName.valueOf("user_info"));
        ArrayList<Put> puts = new ArrayList<>();
        
        for(int i=0;i<100000;i++){
            Put put = new Put(Bytes.toBytes(""+i));
            put.addColumn(Bytes.toBytes("base_info"), Bytes.toBytes("username"), Bytes.toBytes("張三"+i));
            put.addColumn(Bytes.toBytes("base_info"), Bytes.toBytes("age"), Bytes.toBytes((18+i)+""));
            put.addColumn(Bytes.toBytes("extra_info"), Bytes.toBytes("addr"), Bytes.toBytes("北京"));
            
            puts.add(put);
        }
        
        table.put(puts);
        
    }
    
    /**
     * 刪
     * @throws Exception 
     */
    @Test
    public void testDelete() throws Exception{
        Table table = conn.getTable(TableName.valueOf("user_info"));
        
        // 構(gòu)造一個對象封裝要刪除的數(shù)據(jù)信息
        Delete delete1 = new Delete(Bytes.toBytes("001"));
        
        Delete delete2 = new Delete(Bytes.toBytes("002"));
        delete2.addColumn(Bytes.toBytes("extra_info"), Bytes.toBytes("addr"));
        
        ArrayList<Delete> dels = new ArrayList<>();
        dels.add(delete1);
        dels.add(delete2);
        
        table.delete(dels);
        
        
        table.close();
        conn.close();
    }
    
    /**
     * 查
     * @throws Exception 
     */
    @Test
    public void testGet() throws Exception{
        
        Table table = conn.getTable(TableName.valueOf("user_info"));
        
        Get get = new Get("002".getBytes());
        
        Result result = table.get(get);
        
        // 從結(jié)果中取用戶指定的某個key的value
        byte[] value = result.getValue("base_info".getBytes(), "age".getBytes());
        System.out.println(new String(value));
        
        System.out.println("-------------------------");
        
        // 遍歷整行結(jié)果中的所有kv單元格
        CellScanner cellScanner = result.cellScanner();
        while(cellScanner.advance()){
            Cell cell = cellScanner.current();
            
            byte[] rowArray = cell.getRowArray();  //本kv所屬的行鍵的字節(jié)數(shù)組
            byte[] familyArray = cell.getFamilyArray();  //列族名的字節(jié)數(shù)組
            byte[] qualifierArray = cell.getQualifierArray();  //列名的字節(jié)數(shù)據(jù)
            byte[] valueArray = cell.getValueArray(); // value的字節(jié)數(shù)組
            
            System.out.println("行鍵: "+new String(rowArray,cell.getRowOffset(),cell.getRowLength()));
            System.out.println("列族名: "+new String(familyArray,cell.getFamilyOffset(),cell.getFamilyLength()));
            System.out.println("列名: "+new String(qualifierArray,cell.getQualifierOffset(),cell.getQualifierLength()));
            System.out.println("value: "+new String(valueArray,cell.getValueOffset(),cell.getValueLength()));
            
        }
        
        table.close();
        conn.close();
        
    }
    
    
    /**
     * 按行鍵范圍查詢數(shù)據(jù)
     * @throws Exception 
     */
    @Test
    public void testScan() throws Exception{
        
        Table table = conn.getTable(TableName.valueOf("user_info"));
        
        // 包含起始行鍵,不包含結(jié)束行鍵,但是如果真的想查詢出末尾的那個行鍵,那么,可以在末尾行鍵上拼接一個不可見的字節(jié)(\000)
        Scan scan = new Scan("10".getBytes(), "10000\001".getBytes());
        
        ResultScanner scanner = table.getScanner(scan);
        
        Iterator<Result> iterator = scanner.iterator();
        
        while(iterator.hasNext()){
            
            Result result = iterator.next();
            // 遍歷整行結(jié)果中的所有kv單元格
            CellScanner cellScanner = result.cellScanner();
            while(cellScanner.advance()){
                Cell cell = cellScanner.current();
                
                byte[] rowArray = cell.getRowArray();  //本kv所屬的行鍵的字節(jié)數(shù)組
                byte[] familyArray = cell.getFamilyArray();  //列族名的字節(jié)數(shù)組
                byte[] qualifierArray = cell.getQualifierArray();  //列名的字節(jié)數(shù)據(jù)
                byte[] valueArray = cell.getValueArray(); // value的字節(jié)數(shù)組
                
                System.out.println("行鍵: "+new String(rowArray,cell.getRowOffset(),cell.getRowLength()));
                System.out.println("列族名: "+new String(familyArray,cell.getFamilyOffset(),cell.getFamilyLength()));
                System.out.println("列名: "+new String(qualifierArray,cell.getQualifierOffset(),cell.getQualifierLength()));
                System.out.println("value: "+new String(valueArray,cell.getValueOffset(),cell.getValueLength()));
            }
            System.out.println("----------------------");
        }
    }
    
    @Test
    public void test(){
        String a = "000";
        String b = "000\0";
        
        System.out.println(a);
        System.out.println(b);
        
        
        byte[] bytes = a.getBytes();
        byte[] bytes2 = b.getBytes();
        
        System.out.println("");
        
    }
    
    
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 下雨了!淅淅瀝瀝,細(xì)細(xì)的、密密的,斜織著,綿綿何時休! 雨,總是會給人帶來些許愁緒,...
    守候一抹溫情閱讀 209評論 2 1
  • 最近的日志無法做到日更,所以去掉“每日”,修正為覺察日志,這本身也是一種覺察。 為什么不能做到日更,第一是最近的節(jié)...
    韌性十足的牛皮糖閱讀 369評論 0 2
  • (呆在狹小的空間,更能引導(dǎo)人對死亡的思考。)偶然經(jīng)歷了死亡,這個嚴(yán)肅的讓人恐懼的事,可對一個滯銷的寫手來說,這是上...
  • 每日總結(jié)反思: 看了之后明白了通貨膨脹更明白了為什么指數(shù)增長是唯一的出路。核聚的方法真的很正確。 懂得規(guī)則活用規(guī)則...
    為了自由去成長閱讀 346評論 0 0

友情鏈接更多精彩內(nèi)容