HBase(六)HBase整合Hive,数据的备份与MR操作HBase

时间:2023-03-09 15:58:33
HBase(六)HBase整合Hive,数据的备份与MR操作HBase

一.数据的备份与恢复

1. 备份

停止 HBase 服务后,使用 distcp 命令运行 MapReduce 任务进行备份,将数据备份到另一个地方,可以是同一个集群,也可以是专用的备份集群。

即,把数据转移到当前集群的其他目录下(也可以不在同一个集群中):

$ bin/hadoop distcp \ hdfs://node21:8020/hbase \
hdfs://node21:8020/HbaseBackup/backup20180820

尖叫提示:执行该操作,一定要开启 Yarn 服务

2. 恢复

非常简单,与备份方法一样,将数据整个移动回来即可。

$ bin/hadoop distcp \
hdfs://node21:8020/HbaseBackup/backup20180820 \
hdfs://node21:8020/hbase

二.节点的管理

1. 服役(commissioning

当启动 regionserver 时,regionserver 会向 HMaster 注册并开始接收本地数据,开始的时候, 新加入的节点不会有任何数据,平衡器开启的情况下,将会有新的 region 移动到开启的

RegionServer 上。如果启动和停止进程是使用 ssh 和 HBase 脚本,那么会将新添加的节点的主机名加入到 conf/regionservers 文件中。

2. 退役(decommissioning

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

1) 停止负载平衡器

hbase> balance_switch false

2) 在退役节点上停止 RegionServer

hbase> hbase-daemon.sh stop regionserver

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

4) Zookeeper 上的该 RegionServer 节点消失

5) Master 节点检测到该 RegionServer 下线

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

该关闭方法比较传统,需要花费一定的时间,而且会造成部分 region 短暂的不可用。

另一种方案:

1) RegionServer 先卸载所管理的 region

$ bin/graceful_stop.sh <RegionServer-hostname>

2) 自动平衡数据

3) 和之前的 2~6 步是一样的

三. 版本的确界

1. 版本的下界

默认的版本下界是 0,即禁用。row 版本使用的最小数目是与生存时间(TTL Time To Live) 相结合的,并且我们根据实际需求可以有 0 或更多的版本,使用 0,即只有 1 个版本的值写入 cell。

2. 版本的上界

之前默认的版本上界是 3,也就是一个 row 保留 3 个副本(基于时间戳的插入)。该值不要设计的过大,一般的业务不会超过 100。如果 cell 中存储的数据版本号超过了 3 个,再次插入数据时,最新的值会将最老的值覆盖。(现版本已默认为 1)

四.HBase与Hive整合

1. HBase 与 Hive 的对比

1) Hive

(1) 数据仓库

Hive 的本质其实就相当于将 HDFS 中已经存储的文件在 Mysql 中做了一个双射关系,以方便使用 HQL 去管理查询。

(2) 用于数据分析、清洗

Hive 适用于离线的数据分析和清洗,延迟较高。

(3) 基于 HDFSMapReduce

Hive 存储的数据依旧在 DataNode 上,编写的 HQL 语句终将是转换为 MapReduce 代码执行。

2) HBase

(1) 数据库

是一种面向列存储的非关系型数据库。

(2) 用于存储结构化和非结构话的数据

适用于单表非关系型数据的存储,不适合做关联查询,类似 JOIN 等操作。

(3) 基于 HDFS

数据持久化存储的体现形式是 Hfile,存放于 DataNode 中,被 ResionServer 以 region 的形式进行管理。

(4) 延迟较低,接入在线业务使用

面对大量的企业数据,HBase 可以直线单表大量数据的存储,同时提供了高效的数据访问速度。

2. HBase 与 Hive 集成使用

注意:HBase 与 Hive 的集成在版本中兼容问题。

环境准备

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

$ export HBASE_HOME=/opt/modules/hbase-1.2.6
$ export HIVE_HOME=/opt/modules/hive-2.3.3
$ ln -s $HBASE_HOME/lib/hbase-common-1.2.6.jar $HIVE_HOME/lib/hbase-common-1.2.6.jar
$ ln -s $HBASE_HOME/lib/hbase-server-1.2.6.jar $HIVE_HOME/lib/hbase-server-1.2.6.jar
$ ln -s $HBASE_HOME/lib/hbase-client-1.2.6.jar $HIVE_HOME/lib/hbase-client-1.2.6.jar
$ ln -s $HBASE_HOME/lib/hbase-protocol-1.2.6.jar $HIVE_HOME/lib/hbase-protocol-1.2.6.jar
$ ln -s $HBASE_HOME/lib/hbase-it-1.2.6.jar $HIVE_HOME/lib/hbase-it-1.2.6.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.2.6.jar $HIVE_HOME/lib/hbase-hadoop2-compat-1.2.6.jar
$ ln -s $HBASE_HOME/lib/hbase-hadoop-compat-1.2.6.jar $HIVE_HOME/lib/hbase-hadoop-compat-1.2.6.jar

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

<property>
<name>hive.zookeeper.quorum</name>
<value>node21,node22,node23</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>

2.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 查看,都生成了对应的表

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

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

CREATE TABLE 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/data/emp.txt' into table emp;

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

hive> insert into table hive_hbase_emp_table select * from emp;

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

Hive:

hive> select * from hive_hbase_emp_table;

HBase:

hbase> scan ‘hbase_emp_table’

2.2. 案例二

目标:在 HBase 中已经存储了某一张表 hbase_emp_table,然后在 Hive 中创建一个外部表来,

关联 HBase 中的 hbase_emp_table 这张表,使之可以借助 Hive 来分析 HBase 这张表中的数据。

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

(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");

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

hive (default)> select * from relevance_hbase_emp;

五.HBase与Sqoop集成

1. 概念

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

之前我们已经学习过如何使用 Sqoop 在 Hadoop 集群和关系型数据库中进行数据的导入导出

工作,接下来我们学习一下利用 Sqoop 在 HBase 和 RDBMS 中进行数据的转储。

相关参数:

参数

描述

--column-family <family>

Sets the target column family for the import

设置导入的目标列族。

--hbase-create-table

If specified, create missing HBase tables

是否自动创建不存在的 HBase 表(这就意味着,不需要手动提前在 HBase 中先建立表)

--hbase-row-key <col>

Specifies which input column to use as the row key.In case, if input table contains composite key, then <col> must be in the form of a

comma-separated list of composite key attributes.

mysql 中哪一列的值作为 HBase 的 rowkey,

如果rowkey 是个组合键,则以逗号分隔。(注:

避免 rowkey 的重复)

--hbase-table <table-name>

Specifies an HBase table to use as the target instead of HDFS.

指定数据将要导入到 HBase 中的哪张表中。

--hbase-bulkload

Enables bulk loading.

是否允许 bulk 形式的导入。

2. 案例一

目标:将 RDBMS 中的数据抽取到 HBase 中分步实现:

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

export HBASE_HOME=/opt/module/hbase-1.2.6

(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 导入数据的操作

$ bin/sqoop import \
--connect jdbc:mysql://node21:3306/db_library \
--username root \
--password 123456 \
--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.7 只支持 HBase1.0.1 之前的版本的自动创建 HBase 表的功能

解决方案:手动创建 HBase 表

hbase> create 'hbase_book','info'

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

hbase> scan ‘hbase_book’

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

六.HBase操作MapReduce

1.  MapReduce

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

1.1 官方 HBase-MapReduce

1) 查看 HBase 的 MapReduce 任务的执行

$ bin/hbase mapredcp

2) 执行环境变量的导入

$ export HBASE_HOME=/opt/module/hbase-1.2.6
$ export HADOOP_HOME=/opt/module/hadoop-2.7.6
$ export HADOOP_CLASSPATH=`${HBASE_HOME}/bin/hbase mapredcp`

3) 运行官方的 MapReduce 任务

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

$ ~/module/hadoop-2.7.6/bin/yarn jar lib/hbase-server-1.2.6.jar rowcounter student

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

(1) 在本地创建一个 tsv 格式的文件:fruit.tsv

1001

Apple

Red

1002

Pear

Yellow

1003

Pineapple

Yellow

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

(2) 创建 HBase 

hbase(main):001:0> create 'fruit','info'

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

$ ~/module/hadoop-2.7.6/bin/hdfs dfs -mkdir /input_fruit/
$ ~/module/hadoop-2.7.6/bin/hdfs dfs -put fruit.tsv /input_fruit/

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

$ ~/module/hadoop-2.7.6/bin/yarn jar lib/hbase-server-1.2.6.jar importtsv \
-Dimporttsv.columns=HBASE_ROW_KEY,info:name,info:color fruit \ hdfs://node21:8020/input_fruit

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

hbase(main):001:0> scan ‘fruit’

1.2 自定义 HBase-MapReduce1

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

1) 构建 ReadFruitMapper 类,用于读取 fruit 表中的数据

package com.xyg.hbase_mr;

import java.io.IOException;
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; public class ReadFruitMapper extends TableMapper<ImmutableBytesWritable, Put> {
@Override
protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException {

//将 fruit 的 name 和 color 提取出来,相当于将每一行数据读取出来放入到 Put 对象中。
Put put = new Put(key.get());
//遍历添加 column 行
for(Cell cell: value.rawCells()){
//添加/克隆列族:info
if("info".equals(Bytes.toString(CellUtil.cloneFamily(cell)))){
//添加/克隆列:name
if("name".equals(Bytes.toString(CellUtil.cloneQualifier(cell)))){
//将该列 cell 加入到 put 对象中
put.add(cell);
//添加/克隆列:color
}else if("color".equals(Bytes.toString(CellUtil.cloneQualifier(cell)))){
//向该列 cell 加入到 put 对象中
put.add(cell);
}
}
}
//将从 fruit 读取到的每行数据写入到 context 中作为 map 的输出
context.write(key, put);
}
}

2) 构建 WriteFruitMRReducer 类,用于将读取到的 fruit 表中的数据写入到 fruit_mr 表中

package com.z.hbase_mr;
import java.io.IOException;
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;
public class WriteFruitMRReducer extends TableReducer<ImmutableBytesWritable, Put, NullWritable> {
@Override
protected void reduce(ImmutableBytesWritable key, Iterable<Put> values, Context context) throws IOException, InterruptedException {
//读出来的每一行数据写入到 fruit_mr 表中
for(Put put: values){ context.write(NullWritable.get(), put);
}
}
}

3) 构建 Fruit2FruitMRRunner extends Configured implements Tool 用于组装运行 Job 任务

//组装 Job
public int run(String[] args) throws Exception {
//得到 Configuration
Configuration conf = this.getConf();
//创建 Job 任务
Job job = Job.getInstance(conf, this.getClass().getSimpleName());
job.setJarByClass(Fruit2FruitMRRunner.class);
//配置 Job
Scan scan = new Scan();
scan.setCacheBlocks(false);
scan.setCaching(500);
//设置 Mapper,注意导入的是 mapreduce 包下的,不是 mapred 包下的,后者是老版本
TableMapReduceUtil.initTableMapperJob(
"fruit", //数据源的表名
scan, //scan 扫描控制器
ReadFruitMapper.class,//设置 Mapper 类
ImmutableBytesWritable.class,//设置 Mapper 输出 key 类型
Put.class,//设置 Mapper 输出 value 值类型
job//设置给哪个 JOB
);
//设置 Reducer
TableMapReduceUtil.initTableReducerJob("fruit_mr", WriteFruitMRReducer.class,job);
//设置 Reduce 数量,最少 1 个
job.setNumReduceTasks(1);
boolean isSuccess = job.waitForCompletion(true);
if(!isSuccess){
throw new IOException("Job running with error");
}
return isSuccess ? 0 : 1;
}

4) 主函数中调用运行该 Job 任务

public static void main( String[] args ) throws Exception{ 
Configuration conf = HBaseConfiguration.create();
int status = ToolRunner.run(conf, new Fruit2FruitMRRunner(), args);
System.exit(status);

5) 打包运行任务

$ ~/module/hadoop-2.7.6/bin/yarn jar ~/softwares/jars/hbase-0.0.1-SNAPSHOT.jar
com.z.hbase.mr1.Fruit2FruitMRRunner

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

尖叫提示:maven 打包命令:-P local clean package 或-P dev clean package install(将第三方jar 包一同打包,需要插件:maven-shade-plugin)

1.3 自定义 HBase-MapReduce2

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

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

package com.z.hbase.mr2;

import java.io.IOException;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper; public class ReadFruitFromHDFSMapper extends Mapper<LongWritable, Text,ImmutableBytesWritable, Put> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
//从 HDFS 中读取的数据
String lineValue = value.toString();
//读取出来的每行数据使用\t 进行分割,存于 String 数组
String[] values = lineValue.split("\t");
//根据数据中值的含义取值String rowKey = values[0];
String name = values[1];
String color = values[2];
//初始化 rowKey
ImmutableBytesWritable rowKeyWritable = new
ImmutableBytesWritable(Bytes.toBytes(rowKey));
//初始化 put 对象
Put put = new Put(Bytes.toBytes(rowKey));
//参数分别:列族、列、值
put.add(Bytes.toBytes("info"), Bytes.toBytes("name"),Bytes.toBytes(name));
put.add(Bytes.toBytes("info"), Bytes.toBytes("color"),Bytes.toBytes(color));
context.write(rowKeyWritable, put);
}
}

2)构建 WriteFruitMRFromTxtReducer 

package com.z.hbase.mr2;
import java.io.IOException;
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;
public class WriteFruitMRFromTxtReducer extends TableReducer<ImmutableBytesWritable, Put, NullWritable> {
@Override
protected void reduce(ImmutableBytesWritable key, Iterable<Put> values, Context context) throws IOException, InterruptedException {
//读出来的每一行数据写入到 fruit_hdfs 表中
for(Put put: values){ context.write(NullWritable.get(), put);
}
}
}

3)创建 Txt2FruitRunner 组装 Job

public int run(String[] args) throws Exception {
//得到 Configuration
Configuration conf = this.getConf();
//创建 Job 任务
Job job = Job.getInstance(conf, this.getClass().getSimpleName());
job.setJarByClass(Txt2FruitRunner.class);
Path inPath = new Path("hdfs://linux01:8020/input_fruit/fruit.tsv");
FileInputFormat.addInputPath(job, inPath);
// 设 置 Mapper job.setMapperClass(ReadFruitFromHDFSMapper.class);
job.setMapOutputKeyClass(ImmutableBytesWritable.class); job.setMapOutputValueClass(Put.class);
//设置 Reducer
TableMapReduceUtil.initTableReducerJob("fruit_mr", WriteFruitMRFromTxtReducer.class, job);
//设置 Reduce 数量,最少 1 个
job.setNumReduceTasks(1);
boolean isSuccess = job.waitForCompletion(true);
if(!isSuccess){
throw new IOException("Job running with error");
}
return isSuccess ? 0 : 1; }

4) 调用执行 Job

public static void main(String[] args) throws Exception { Configuration conf = HBaseConfiguration.create();
int status = ToolRunner.run(conf, new Txt2FruitRunner(), args); System.exit(status);

5) 打包运行

$ ~/module/hadoop-2.7.6/bin/yarn jar ~/softwares/jars/hbase-0.0.1-SNAPSHOT.jar
com.z.hbase.mr2.Txt2FruitRunner

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

尖叫提示:maven 打包命令:-P local clean package 或-P dev clean package install(将第三方

jar 包一同打包,需要插件:maven-shade-plugin)

2. MapReduce从HDFS读取数据存储到HBase中

现有HDFS中有一个student.txt文件,格式如下

95002,刘晨,女,19,IS
95017,王风娟,女,18,IS
95018,王一,女,19,IS
95013,冯伟,男,21,CS
95014,王小丽,女,19,CS
95019,邢小丽,女,19,IS
95020,赵钱,男,21,IS
95003,王敏,女,22,MA
95004,张立,男,19,IS
95012,孙花,女,20,CS
95010,孔小涛,男,19,CS
95005,刘刚,男,18,MA
95006,孙庆,男,23,CS
95007,易思玲,女,19,MA
95008,李娜,女,18,CS
95021,周二,男,17,MA
95022,郑明,男,20,MA
95001,李勇,男,20,CS
95011,包小柏,男,18,MA
95009,梦圆圆,女,18,MA
95015,王君,男,18,MA

将HDFS上的这个文件里面的数据写入到HBase数据块中

MapReduce实现代码如下

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner; public class ReadHDFSDataToHbaseMR extends Configured implements Tool{ public static void main(String[] args) throws Exception { int run = ToolRunner.run(new ReadHDFSDataToHbaseMR(), args);
System.exit(run);
} @Override
public int run(String[] arg0) throws Exception { Configuration conf = HBaseConfiguration.create();
conf.set("fs.defaultFS", "hdfs://myha01/");
conf.set("hbase.zookeeper.quorum", "node21:2181,node22:2181,node23:2181");
System.setProperty("HADOOP_USER_NAME", "admin");
FileSystem fs = FileSystem.get(conf);
// conf.addResource("config/core-site.xml");
// conf.addResource("config/hdfs-site.xml"); Job job = Job.getInstance(conf); job.setJarByClass(ReadHDFSDataToHbaseMR.class); job.setMapperClass(HDFSToHbaseMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(NullWritable.class); TableMapReduceUtil.initTableReducerJob("student", HDFSToHbaseReducer.class, job,null,null,null,null,false);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(Put.class); Path inputPath = new Path("/student/input/");
Path outputPath = new Path("/student/output/"); if(fs.exists(outputPath)) {
fs.delete(outputPath,true);
} FileInputFormat.addInputPath(job, inputPath);
FileOutputFormat.setOutputPath(job, outputPath); boolean isDone = job.waitForCompletion(true); return isDone ? 0 : 1;
} public static class HDFSToHbaseMapper extends Mapper<LongWritable, Text, Text, NullWritable>{ @Override
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
context.write(value, NullWritable.get());
} } /**
* 95015,王君,男,18,MA
* */
public static class HDFSToHbaseReducer extends TableReducer<Text, NullWritable, NullWritable>{ @Override
protected void reduce(Text key, Iterable<NullWritable> values,Context context)
throws IOException, InterruptedException { String[] split = key.toString().split(","); Put put = new Put(split[0].getBytes()); put.addColumn("info".getBytes(), "name".getBytes(), split[1].getBytes());
put.addColumn("info".getBytes(), "sex".getBytes(), split[2].getBytes());
put.addColumn("info".getBytes(), "age".getBytes(), split[3].getBytes());
put.addColumn("info".getBytes(), "department".getBytes(), split[4].getBytes()); context.write(NullWritable.get(), put); } } }

3. MapReduce从HBase读取数据计算平均年龄并存储到HDFS中

import java.io.IOException;
import java.util.List; import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Result;
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.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner; public class ReadHbaseDataToHDFS extends Configured implements Tool{ public static void main(String[] args) throws Exception { int run = ToolRunner.run(new ReadHbaseDataToHDFS(), args);
System.exit(run); } @Override
public int run(String[] arg0) throws Exception { Configuration conf = HBaseConfiguration.create();
conf.set("fs.defaultFS", "hdfs://myha01/");
conf.set("hbase.zookeeper.quorum", "node21:2181,node22:2181,node23:2181");
System.setProperty("HADOOP_USER_NAME", "admin");
FileSystem fs = FileSystem.get(conf);
// conf.addResource("config/core-site.xml");
// conf.addResource("config/hdfs-site.xml"); Job job = Job.getInstance(conf); job.setJarByClass(ReadHbaseDataToHDFS.class); // 取对业务有用的数据 info,age
Scan scan = new Scan();
scan.addColumn("info".getBytes(), "age".getBytes()); TableMapReduceUtil.initTableMapperJob(
"student".getBytes(), // 指定表名
scan, // 指定扫描数据的条件
HbaseToHDFSMapper.class, // 指定mapper class
Text.class, // outputKeyClass mapper阶段的输出的key的类型
IntWritable.class, // outputValueClass mapper阶段的输出的value的类型
job, // job对象
false
); job.setReducerClass(HbaseToHDFSReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(DoubleWritable.class); Path outputPath = new Path("/student/avg/"); if(fs.exists(outputPath)) {
fs.delete(outputPath,true);
} FileOutputFormat.setOutputPath(job, outputPath); boolean isDone = job.waitForCompletion(true); return isDone ? 0 : 1;
} public static class HbaseToHDFSMapper extends TableMapper<Text, IntWritable>{ Text outKey = new Text("age");
IntWritable outValue = new IntWritable();
// key是hbase中的行键
// value是hbase中的所行键的所有数据
@Override
protected void map(ImmutableBytesWritable key, Result value,Context context)
throws IOException, InterruptedException { boolean isContainsColumn = value.containsColumn("info".getBytes(), "age".getBytes()); if(isContainsColumn) { List<Cell> listCells = value.getColumnCells("info".getBytes(), "age".getBytes());
System.out.println("listCells:\t"+listCells);
Cell cell = listCells.get(0);
System.out.println("cells:\t"+cell); byte[] cloneValue = CellUtil.cloneValue(cell);
String ageValue = Bytes.toString(cloneValue);
outValue.set(Integer.parseInt(ageValue)); context.write(outKey,outValue); } } } public static class HbaseToHDFSReducer extends Reducer<Text, IntWritable, Text, DoubleWritable>{ DoubleWritable outValue = new DoubleWritable(); @Override
protected void reduce(Text key, Iterable<IntWritable> values,Context context)
throws IOException, InterruptedException { int count = 0;
int sum = 0;
for(IntWritable value : values) {
count++;
sum += value.get();
} double avgAge = sum * 1.0 / count;
outValue.set(avgAge);
context.write(key, outValue);
} } }