整个项目以hadoop自带的hadoop-mapreduce-examples-2.6.0.jar为例。
2.1新建一个项目
说明:这里没有使用hadoop-eclipse-plugin插件,而是直接新建一个java project,和hadoop-mapreduce-examples-2.6.0.jar一样,完成后打包成jar文件在hadoop集群中运行。
打开eclipse,file---new---java project
2.2新建一个lib文件夹,并将hadoop三个jar复制进去
三个jar包所在hadoop的路径:
hadoop/share/hadoop/yarn/lib/commons-cli-1.2.jar
hadoop/share/hadoop/common/hadoop-common-2.6.0.jar
hadoop/share/hadoop/mapreduce/hadoop-mapreduce-client-core-2.6.0.jar
2.3将三个jar包add to build path
2.2jar包入口class
最终我们会将项目打包成一个jar文件放到hadoop集群中去运行。但是在打包jar文件的时候只能指定一个main class,那么每一个需求就要打包成一个jar文件,在使用管理上都很麻烦。通过模仿hadoop自带的样例hadoop-mapreduce-examples-2.6.0.jar,我们可以为jar包创建一个统一的man class,再通过它去调用其他的man class。
-
package exhadp;
-
-
import org.apache.hadoop.util.ProgramDriver;
-
-
public class hadpdriver {
-
-
public static void main(String[] args) {
-
// TODO Auto-generated method stub
-
-
int exitCode=-1;
-
ProgramDriver pdg=new ProgramDriver();
-
-
try{
-
pdg.addClass("getcount", getcount.class, "getcount");
-
pdg.addClass("getmax", getmax.class, "getmax");
-
pdg.addClass("getsum", getsum.class, "getsum");
-
exitCode=pdg.run(args);
-
}catch (Throwable e){
-
e.printStackTrace();
-
}
-
-
System.exit(exitCode);
-
}
-
}
调用的方式如下:
[grid@dehadp01 ~]$ hadoop jar exhadp.jar getsum TEST_OBJECTS/part-m-00000 getsum_out
2.3案例文件说明
1,SYS,ICOL$,null,20,2,TABLE,2011-09-17 09:46:13.0,2011-09-17 09:58:00.0,2011-09-17:09:46:13,VALID,N,N,N,1,null
2,SYS,I_USER1,null,46,46,INDEX,2011-09-17 09:46:13.0,2011-09-17 09:46:13.0,2011-09-17:09:46:13,VALID,N,N,N,4,null
3,SYS,CON$,null,28,28,TABLE,2011-09-17 09:46:13.0,2011-09-17 10:04:20.0,2011-09-17:09:46:13,VALID,N,N,N,1,null
4,SYS,UNDO$,null,15,15,TABLE,2011-09-17 09:46:13.0,2011-09-17 09:46:13.0,2011-09-17:09:46:13,VALID,N,N,N,1,null
5,SYS,C_COBJ#,null,29,29,CLUSTER,2011-09-17 09:46:13.0,2011-09-17 09:46:13.0,2011-09-17:09:46:13,VALID,N,N,N,5,null
数据源于oracle数据库内的:select rownum id,a.* from dba_objects a
每一行即是一条记录,中间以“,”分隔,第一列表示id,第二列表示owner,第七列表示object_type,倒数第二列表示status。
2.4求每个owner的最大的id,即select owner,max(id) from t group by owner
-
package exhadp;
-
-
//完全模仿wordcount的样式
-
-
import java.io.IOException;
-
-
import org.apache.hadoop.conf.Configuration;
-
import org.apache.hadoop.fs.Path;
-
import org.apache.hadoop.io.IntWritable;
-
import org.apache.hadoop.io.Text;
-
import org.apache.hadoop.mapreduce.Job;
-
import org.apache.hadoop.mapreduce.Mapper;
-
import org.apache.hadoop.mapreduce.Reducer;
-
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
-
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
-
import org.apache.hadoop.util.GenericOptionsParser;
-
-
public class getmax {
-
-
// map的过程
-
public static class TokenizerMapper extends
-
Mapper<Object, Text, Text, IntWritable> {
-
public void map(Object key, Text value,
-
Mapper<Object, Text, Text, IntWritable>.Context context)
-
throws IOException, InterruptedException {
-
// 将源文件中一行的记录以字符串的形式存入line中
-
String line = value.toString();
-
String[] strarray = line.split(",");
-
// 以“,”为分隔符,第一列(strarray[0])为id,第二列(strarray[1])为owner
-
Text owner = new Text(strarray[1]);
-
int id = Integer.parseInt(strarray[0]);
-
// 将owner做为map的key,id作为value
-
context.write(owner, new IntWritable(id));
-
}
-
}
-
-
// reduce过程
-
public static class IntMaxReducer extends
-
Reducer<Text, IntWritable, Text, IntWritable> {
-
public void reduce(Text key, Iterable<IntWritable> values,
-
Reducer<Text, IntWritable, Text, IntWritable>.Context context)
-
throws IOException, InterruptedException {
-
int max = Integer.MIN_VALUE;
-
for (IntWritable value : values) {
-
max = Math.max(max, value.get());
-
}
-
context.write(key, new IntWritable(max));
-
}
-
}
-
-
// 主程序分别调用map和reduce的过程
-
public static void main(String[] args) throws Exception {
-
Configuration conf = new Configuration();
-
String[] otherArgs = new GenericOptionsParser(conf, args)
-
.getRemainingArgs();
-
if (otherArgs.length < 2) {
-
System.err.println("Usage: getmax <in> [<in>...] <out>");
-
System.exit(2);
-
}
-
Job job = new Job(conf, "getmax");
-
job.setJarByClass(getmax.class);
-
job.setMapperClass(TokenizerMapper.class);
-
job.setCombinerClass(IntMaxReducer.class);
-
job.setReducerClass(IntMaxReducer.class);
-
job.setOutputKeyClass(Text.class);
-
job.setOutputValueClass(IntWritable.class);
-
for (int i = 0; i < otherArgs.length - 1; i++) {
-
FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
-
}
-
FileOutputFormat.setOutputPath(job, new Path(
-
otherArgs[(otherArgs.length - 1)]));
-
-
System.exit(job.waitForCompletion(true) ? 0 : 1);
-
}
-
}
2.5统计每种status的数量,即select status,count(*) from t group by status
-
package exhadp;
-
-
import java.io.IOException;
-
-
import org.apache.hadoop.conf.Configuration;
-
import org.apache.hadoop.fs.Path;
-
import org.apache.hadoop.io.IntWritable;
-
import org.apache.hadoop.io.Text;
-
import org.apache.hadoop.mapreduce.Job;
-
import org.apache.hadoop.mapreduce.Mapper;
-
import org.apache.hadoop.mapreduce.Reducer;
-
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
-
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
-
import org.apache.hadoop.util.GenericOptionsParser;
-
-
public class getcount {
-
-
public static void main(String[] args) throws Exception {
-
Configuration conf = new Configuration();
-
String[] otherArgs = new GenericOptionsParser(conf, args)
-
.getRemainingArgs();
-
if (otherArgs.length < 2) {
-
System.err.println("Usage: getcount <in> [<in>...] <out>");
-
System.exit(2);
-
}
-
Job job = new Job(conf, "getcount");
-
job.setJarByClass(getcount.class);
-
job.setMapperClass(TokenizerMapper.class);
-
job.setCombinerClass(IntCountReducer.class);
-
job.setReducerClass(IntCountReducer.class);
-
job.setOutputKeyClass(Text.class);
-
job.setOutputValueClass(IntWritable.class);
-
for (int i = 0; i < otherArgs.length - 1; i++) {
-
FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
-
}
-
FileOutputFormat.setOutputPath(job, new Path(
-
otherArgs[(otherArgs.length - 1)]));
-
-
System.exit(job.waitForCompletion(true) ? 0 : 1);
-
}
-
-
public static class IntCountReducer extends
-
Reducer<Text, IntWritable, Text, IntWritable> {
-
public void reduce(Text key, Iterable<IntWritable> values,
-
Reducer<Text, IntWritable, Text, IntWritable>.Context context)
-
throws IOException, InterruptedException {
-
int count = 0;
-
for (IntWritable value : values) {
-
// 这里count累加value的值(就是1),这样就可以统计出总数出来了
-
count = count + value.get();
-
}
-
context.write(key, new IntWritable(count));
-
}
-
}
-
-
public static class TokenizerMapper extends
-
Mapper<Object, Text, Text, IntWritable> {
-
public void map(Object key, Text value,
-
Mapper<Object, Text, Text, IntWritable>.Context context)
-
throws IOException, InterruptedException {
-
String line = value.toString();
-
String[] strarray = line.split(",");
-
Text status = new Text(strarray[10]);
-
// 取第11列的status的值作为map的key,因为只是统计count,所以使用一个常量1作为map的value就可以了
-
context.write(status, new IntWritable(1));
-
}
-
}
-
-
}
2.6求每个object_type的id和,即select object_type,sum(id) from t group by object_type
新加入了LINESKIP,在map阶段用来统计出错的行;运行阶段加入了运行耗时
-
package exhadp;
-
-
import java.io.IOException;
-
import java.text.DateFormat;
-
import java.text.SimpleDateFormat;
-
import java.util.Date;
-
-
import org.apache.hadoop.conf.Configuration;
-
import org.apache.hadoop.conf.Configured;
-
import org.apache.hadoop.fs.Path;
-
import org.apache.hadoop.io.Text;
-
import org.apache.hadoop.mapreduce.Job;
-
import org.apache.hadoop.mapreduce.Mapper;
-
import org.apache.hadoop.mapreduce.Reducer;
-
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
-
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
-
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
-
import org.apache.hadoop.util.Tool;
-
import org.apache.hadoop.util.ToolRunner;
-
-
public class getsum extends Configured implements Tool {
-
-
enum Counter {
-
LINESKIP, // 出错的行
-
}
-
-
public int run(String[] args) throws Exception {
-
Configuration conf = new Configuration();
-
-
Job job = new Job(conf, "getsum"); // 任务名
-
job.setJarByClass(getsum.class); // 指定Class
-
-
FileInputFormat.addInputPath(job, new Path(args[0])); // 输入路径
-
FileOutputFormat.setOutputPath(job, new Path(args[1])); // 输出路径
-
-
job.setMapperClass(Map.class); // 调用上面Map类作为Map任务代码
-
job.setReducerClass(Reduce.class); // 调用上面Reduce类作为Reduce任务代码
-
job.setOutputFormatClass(TextOutputFormat.class);
-
job.setOutputKeyClass(Text.class); // 指定输出的KEY的格式
-
job.setOutputValueClass(Text.class); // 指定输出的VALUE的格式
-
-
job.waitForCompletion(true);
-
-
// 输出任务完成情况
-
System.out.println("任务名称:" + job.getJobName());
-
System.out.println("任务成功:" + (job.isSuccessful() ? "是" : "否"));
-
System.out.println("输入行数:"
-
+ job.getCounters()
-
.findCounter("org.apache.hadoop.mapred.Task$Counter",
-
"MAP_INPUT_RECORDS").getValue());
-
System.out.println("输出行数:"
-
+ job.getCounters()
-
.findCounter("org.apache.hadoop.mapred.Task$Counter",
-
"MAP_OUTPUT_RECORDS").getValue());
-
System.out.println("跳过的行:"
-
+ job.getCounters().findCounter(Counter.LINESKIP).getValue());
-
-
return job.isSuccessful() ? 0 : 1;
-
}
-
-
/**
-
* 设置系统说明 设置MapReduce任务
-
*/
-
public static void main(String[] args) throws Exception {
-
-
// 判断参数个数是否正确
-
// 如果无参数运行则显示以作程序说明
-
if (args.length != 2) {
-
System.err.println("");
-
System.err.println("Usage: getsum < input path > < output path > ");
-
System.err
-
.println("Example: hadoop jar exhadp.jar hdfs://localhost:9000/home/james/Test_2 hdfs://localhost:9000/home/james/output");
-
System.err.println("Counter:");
-
System.err.println("\t" + "LINESKIP" + "\t"
-
+ "Lines which are too short");
-
System.exit(-1);
-
}
-
-
// 记录开始时间
-
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-
Date start = new Date();
-
-
// 运行任务
-
int res = ToolRunner.run(new Configuration(), new getsum(), args);
-
-
// 输出任务耗时
-
Date end = new Date();
-
float time = (float) ((end.getTime() - start.getTime()) / 60000.0);
-
System.out.println("任务开始:" + formatter.format(start));
-
System.out.println("任务结束:" + formatter.format(end));
-
System.out.println("任务耗时:" + String.valueOf(time) + " 分钟");
-
-
System.exit(res);
-
}
-
-
public static class Reduce extends Reducer<Text, Text, Text, Text> {
-
public void reduce(Text key, Iterable<Text> values, Context context)
-
throws IOException, InterruptedException {
-
-
int sum = 0;
-
-
for (Text value : values) {
-
sum = sum + Integer.parseInt(value.toString());
-
}
-
-
context.write(key, new Text(Integer.toString(sum)));
-
}
-
}
-
-
public static class Map extends Mapper<Object, Text, Text, Text> {
-
public void map(Object key, Text value, Context context)
-
throws IOException, InterruptedException {
-
String line = value.toString(); // 读取源数据
-
String[] strarray = line.split(",");
-
try {
-
Text status = new Text(strarray[6]);
-
Text id = new Text(strarray[0]);
-
-
context.write(status, id);
-
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
-
context.getCounter(Counter.LINESKIP).increment(1); // 出错令计数器+1
-
return;
-
}
-
}
-
}
-
}
2.7导出并运行jar包
导出jar包





将生成的jar文件复制到hadoop集群中即可运行:
[grid@dehadp01 ~]$ hadoop jar exhadp.jar getsum TEST_OBJECTS/part-m-00000 getsum_out
15/07/30 16:30:01 WARN mapreduce.JobSubmitter: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
15/07/30 16:30:01 INFO input.FileInputFormat: Total input paths to process : 1
15/07/30 16:30:01 INFO mapreduce.JobSubmitter: number of splits:1
15/07/30 16:30:02 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1437633633589_0067
15/07/30 16:30:02 INFO impl.YarnClientImpl: Submitted application application_1437633633589_0067
15/07/30 16:30:02 INFO mapreduce.Job: The url to track the job: http://dehadp01:8088/proxy/application_1437633633589_0067/
15/07/30 16:30:02 INFO mapreduce.Job: Running job: job_1437633633589_0067
15/07/30 16:30:11 INFO mapreduce.Job: Job job_1437633633589_0067 running in uber mode : false
15/07/30 16:30:11 INFO mapreduce.Job: map 0% reduce 0%
15/07/30 16:30:20 INFO mapreduce.Job: map 100% reduce 0%
15/07/30 16:30:29 INFO mapreduce.Job: map 100% reduce 100%
15/07/30 16:30:29 INFO mapreduce.Job: Job job_1437633633589_0067 completed successfully
15/07/30 16:30:29 INFO mapreduce.Job: Counters: 49
File System Counters
FILE: Number of bytes read=1253658
FILE: Number of bytes written=2723009
FILE: Number of read operations=0
FILE: Number of large read operations=0
FILE: Number of write operations=0
HDFS: Number of bytes read=10921559
HDFS: Number of bytes written=785
HDFS: Number of read operations=6
HDFS: Number of large read operations=0
HDFS: Number of write operations=2
Job Counters
Launched map tasks=1
Launched reduce tasks=1
Data-local map tasks=1
Total time spent by all maps in occupied slots (ms)=6421
Total time spent by all reduces in occupied slots (ms)=6858
Total time spent by all map tasks (ms)=6421
Total time spent by all reduce tasks (ms)=6858
Total vcore-seconds taken by all map tasks=6421
Total vcore-seconds taken by all reduce tasks=6858
Total megabyte-seconds taken by all map tasks=6575104
Total megabyte-seconds taken by all reduce tasks=7022592
Map-Reduce Framework
Map input records=75942
Map output records=75942
Map output bytes=1101768
Map output materialized bytes=1253658
Input split bytes=115
Combine input records=0
Combine output records=0
Reduce input groups=44
Reduce shuffle bytes=1253658
Reduce input records=75942
Reduce output records=44
Spilled Records=151884
Shuffled Maps =1
Failed Shuffles=0
Merged Map outputs=1
GC time elapsed (ms)=105
CPU time spent (ms)=8210
Physical memory (bytes) snapshot=444616704
Virtual memory (bytes) snapshot=2427170816
Total committed heap usage (bytes)=306708480
Shuffle Errors
BAD_ID=0
CONNECTION=0
IO_ERROR=0
WRONG_LENGTH=0
WRONG_MAP=0
WRONG_REDUCE=0
File Input Format Counters
Bytes Read=10921444
File Output Format Counters
Bytes Written=785
任务名称:getsum
任务成功:是
输入行数:75942
输出行数:75942
跳过的行:0
任务开始:2015-07-30 16:29:58
任务结束:2015-07-30 16:30:29
任务耗时:0.52346665 分钟
[grid@dehadp01 ~]$ hadoop fs -cat getsum_out/part-r-00000
CLUSTER 2607
CONSUMER GROUP 309547
CONTEXT 233362
DESTINATION 24817
DIRECTORY 84148
EDITION 99
EVALUATION CONTEXT 342371
FUNCTION 14181134
INDEX 256715660
INDEX PARTITION 18627058
INDEXTYPE 524538
JAVA CLASS 867243753
JAVA DATA 17401769
JAVA RESOURCE 44179866
JAVA SOURCE 111708
JOB 315526
JOB CLASS 220990
LIBRARY 4042643
LOB 68668545
LOB PARTITION 11075
MATERIALIZED VIEW 68788
OPERATOR 2573501
PACKAGE 52912299
PACKAGE BODY 52093978
PROCEDURE 4944329
PROGRAM 245410
QUEUE 1207189
RESOURCE PLAN 123925
RULE 12864
RULE SET 471244
SCHEDULE 37694
SCHEDULER GROUP 50096
SEQUENCE 6181131
SYNONYM 993156532
TABLE 124894005
TABLE PARTITION 75556978
TABLE SUBPARTITION 281680
TRIGGER 43385559
TYPE 110249150
TYPE BODY 9475369
UNDEFINED 136498
VIEW 109084203
WINDOW 112671
XML SCHEMA 3135344
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/20777547/viewspace-1760222/
,如需转载,请注明出处,否则将追究法律责任。