设置和清理方法究竟用于什么?我试图找出他们的意思,但还没有人能够准确描述他们的所作所为.例如,设置方法如何使用输入拆分中的数据?它作为一个整体吗?还是一行一行?
Jan*_*yne 24
如前所述,setup()并且cleanup()都可以覆盖,如果你选择的方法,他们在那里为您初始化和清理你的map/reduce任务.在这些阶段,您实际上无法直接访问输入拆分中的任何数据.map/reduce任务的生命周期是(从程序员的角度来看):
设置 - >地图 - >清理
setup - > reduce - > cleanup
在此期间通常会发生的setup()是您可以从配置对象中读取参数以自定义处理逻辑.
通常发生的事情cleanup()是您清理可能已分配的任何资源.还有其他用途,即清除聚合结果的任何累积.
该setup()和cleanup()方法是简单的"钩子"为您,开发人员/程序员,之前和之后你的map/reduce任务有机会做一些事情.
例如,在规范单词计数示例中,假设您要排除某些单词不被计算(例如,停止单词,如"the","a","be"等等).配置MapReduce作业时,可以将这些单词的列表(逗号分隔)作为参数(键值对)传递到配置对象中.然后在地图代码中setup(),您可以获取停用词并将它们存储在某个全局变量(全局变量到地图任务)中,并在地图逻辑中排除计算这些单词.以下是http://wiki.apache.org/hadoop/WordCount的修改示例.
public class WordCount {
public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
private Set<String> stopWords;
protected void setup(Context context) throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
stopWords = new HashSet<String>();
for(String word : conf.get("stop.words").split(",")) {
stopWords.add(word);
}
}
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if(stopWords.contains(token)) {
continue;
}
word.set(tokenizer.nextToken());
context.write(word, one);
}
}
}
public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
context.write(key, new IntWritable(sum));
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.set("stop.words", "the, a, an, be, but, can");
Job job = new Job(conf, "wordcount");
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.waitForCompletion(true);
}
}
Run Code Online (Sandbox Code Playgroud)
每个任务都会调用一次设置和清理。
例如,您有 5 个正在运行的映射器,对于每个映射器您想要初始化一些值,那么您可以使用 setup.json 。您的设置方法被调用 5 次。
因此,对于每个mapreduce,首先setup()调用方法,然后map()/reduce()调用方法,最后cleanup()调用方法,然后退出任务。
| 归档时间: |
|
| 查看次数: |
16193 次 |
| 最近记录: |