业务:获取hbase中的某些数据,根据不同维度计算均值、峰值、总量,并将处理结果存储到hbase表中
因为公司是内网,纯手打,可能有错字、错误的代码拼写,望见谅,欢迎指出相关错误。
Configuration conf = new HBaseConfiguration.create();
Scan scan = new Scan();
//然后添加相关scan条件、起始rowkey、过滤器、列族等等
scan.setCaching(DEFAULT_CACHING_SIZE); //实际取出记录数,大时会加快速度,消耗内存
//获取job实例
Job job = Job.getInstance(conf,"最好取个不重复的名字");
job.setJarByClass(AppMap.class);
//获取表名
String table = 'table';
//创建查询hbase的mapper,设置表名、scan、mapper类、mapper的输出key、mapper的输出value、job
TableMapReduceUtil.initTableMapperJob(table,scan,AppMap.class,Text.class,Text.class,job);
//创建查询hbase的reducer,指定表名、reducer类、job
TableMapReduceUtil.initTableReducerJob(table,AppReduce.class,job);
job.setMapperClass(AppMap.class);
job.setReducerClass(AppReduce.class);
//下面这配置一定要注释掉,不然会报wrong.key class 异常
//job.setCombinerClass(AppReucer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
if(job == null){
System.err.println("cannot create job");
System.exit(-1);
}
try{
System.out.println("IsCompletion ==== "+job.waitForCompletion(true));
if(!(job.waitForCompletion(true))){
System.exit(1);
}
}catch(IOException e){
e.printStackTrace();
}catch(ClasNotFoundException e){
e.printStackTrace();
}catch(InterruptedException e){
e.printStackTrace();
}
}
/*
*Text: mapper的输出key类型; IntWritable:mapper的输出value类型
*/
public class AppMap extends TableMapper
/*
* rowkey: rowkey; value: resultscan遍历后的result的一行数据 context:上下文
*/
@Override
protected void map(ImmutableBytesWritable key,Result value,Context)throws IOException,InterruptedException{
//在map层中获取main处的参数(reducer层也是这么获取来自map层的参数)
String param = context.getConfiguration().get("param");
context.write(new Text(Bytes.toBytes(rowkey)),value)
}
/*
* Text:reduce的输入key; IntWritable: reduce的输入value; ImmtableBytesWritable : reduce输出到hbase的rowkey类型
*/
public class AppReduce extends TableReducer
/*
* key: reduce的输入key; values: reduce的输入value; context:联系上下文
*/
@Override
protected void reduce()thorows IOException,InterruptedException{
//获取来自tableMapper的参数同tableMapper层获取方式
//将数据存入hbase
//自定义rowkey
String rowkey = 'key';
//创建put,设置rowkey
Put put = new Put(Bytes.toBytes(rowkey));
put.add(Bytes.toBytes("CF"),Bytes.toBytes("C"),Bytes.toBytes("值"));
// 写到hbase,指定rowkey、put
context.write(new ImmutableBytesWritable(Bytes.toBytes(rowkey)),put);
}
}