文章目录
12、HBase与MapReduce的集成
HBase当中的数据最终都是存储在HDFS上面的,HBase天生的支持MR的操作,我们可以通过MR直接处理HBase当中的数据,并且MR可以将处理后的结果直接存储到HBase当中去
需求:读取HBase当中一张表的数据,然后将数据写入到HBase当中的另外一张表当中去。注意:我们可以使用TableMapper与TableReducer来实现从HBase当中读取与写入数据
http://hbase.apache.org/2.0/book.html#mapreduce
需求一:读取myuser这张表当中的数据写入到HBase的另外一张表当中去
这里我们将myuser这张表当中f1列族的name和age字段写入到myuser2这张表的f1列族当中去
第一步:创建myuser2这张表
注意:列族的名字要与myuser表的列族名字相同
hbase(main):010:0> create ‘myuser2’,‘f1’
第二步:创建maven工程,导入jar包
注意:在之前工程导入jar包的基础上,添加以下这些jar包即可
<!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-mapreduce -->
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-mapreduce</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version> 2.7.5</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.7.5</version>
</dependency>
第三步:开发MR的程序
定义mapper类
public class HBaseMapper extends TableMapper<Text,Put> {
/**
* @param key rowkey
* @param value 封装了我们一行数据
* @param context
* @throws IOException
* @throws InterruptedException
*/
@Override
protected void map(ImmutableBytesWritable key, Result value, Context context)
throws IOException, InterruptedException {
// f1 name age f2 xxx
//获取到我们的rowkey
byte[] bytes = key.get();
Put put = new Put(bytes);
//获取Result当中所有的列
List<Cell> cells = value.listCells();
for (Cell cell : cells) {
//判断属于哪一个列族
byte[] family = CellUtil.cloneFamily(cell);
//获取cell属于哪一个列
byte[] qualifier = CellUtil.cloneQualifier(cell);
if(Bytes.toString(family).equals("f1")){
if(Bytes.toString(qualifier).equals("name") ||
Bytes.toString(qualifier).equals("age")){
put.add(cell);
}
}
}
if(!put.isEmpty()){
context.write(new Text(Bytes.toString(bytes)),put);
}
}
}
定义reducer类
/**
* Text key2的类型
* Put value2类型
* ImmutableBytesWritable k3的类型
* V3的类型???
* put 'myuser2','rowkey','f1:name','zhangsan'
* javaAPI来写通过put对象即可
*
*/
public class HBaseReducer extends TableReducer<Text,Put,ImmutableBytesWritable> {
/**
*
* @param key 就是我们的key2
* @param values 就是我们的v2
* @param context 将我们的数据往外写出去
* @throws IOException
* @throws InterruptedException
*/
@Override
protected void reduce(Text key, Iterable<Put> values, Context context)
throws IOException, InterruptedException {
for (Put put : values) {
context.write(new ImmutableBytesWritable(key.toString().getBytes()),put);
}
}
}
定义程序运行main方法
public class HBaseMrMain extends Configured implements Tool {
@Override
public int run(String[] args) throws Exception {
Job job = Job.getInstance(super.getConf(), "hbaseMR");
Scan scan = new