标签:extend rabl int ima key 单元测试 使用 highlight cer

通过命令行访问刚刚上传至HDFS的数据集
[hadoop@master hadoop-2.6.0]$ bin/hdfs dfs -ls /anagram/

MapReduce程序编译及运行:
第一步:在 Map 阶段,对每个word(单词)按字母进行排序生成sortedWord,然后输出key/value键值对(sortedWord,word)。
//写Map过程
public static class Anagramsmapper extends Mapper<LongWritable, Text, Text, Text> {
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String text = value.toString(); //将输入的Text类型的字母表value转为String类型
char[] textCharArray = text.toCharArray(); //把String类型的字母表转成字符数组
Arrays.sort(textCharArray); //对字符数组进行排序
String sortedText = new String(textCharArray); //将排序后的字符数组,转成String字符串
context.write(new Text(sortedText), value); //写入context,输出key(排序后的字母表)和输出value(原始字母表)
}
}
第二步:在 Reduce 阶段,统计出每组相同字母组成的所有anagrams(字谜)。
//写Reduce过程
public static class Anagramsreducer extends Reducer<Text, Text, Text, Text> {
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
StringBuffer res = new StringBuffer(); //新建一个空的StringBuffer实例res
int count = 0; //计数器初始值为0
//开始遍历values里的值
for (Text text : values) {
//如果res数组里面有值,添加新值的时候先加的一个“,”号作分割符
if(res.length() > 0) {
res.append(",");
}
//往res里添加values里的值
res.append(text);
//计数
count++;
}
//必须有两个或者两个以上相同字母组成的单词,才显示
if(count > 1) {
context.write(key, new Text(res.toString()));
}
}
}
第三步:对代码进行单元测试及debug调试。
public class AnagramsMapperTest {
private Mapper mapper;
private MapDriver driver;
@Before
public void init() {
mapper = new Anagrams.Anagramsmapper();
driver = new MapDriver(mapper);
}
@Test
public void test() throws IOException {
String line = "gfedcba"; //自定这个字母,验证输出结果是否会正确排序
driver.withInput(new LongWritable(), new Text(line))
.withOutput(new Text("abcdefg"),new Text("gfedcba")) //验证输出Key是否进行了字母排序,输出Value不变
.runTest();
}
}
public class AnagramsReduceTest {
private Reducer reducer;
private ReduceDriver driver;
@Before
public void init() {
reducer = new Anagrams.Anagramsreducer();
driver = new ReduceDriver(reducer);
}
@Test
public void test() throws IOException {
Text key = new Text("abcdefg"); //新建一个Key,输出固定不变
List values = new ArrayList(); //在新建数组列表中写入4组字母的Value值,目的验证其最后是否按预定格式输出
values.add(new Text("gfedcba"));
values.add(new Text("decgfba"));
values.add(new Text("fedgcba"));
values.add(new Text("gcbfeda"));
driver.withInput(key, values)
.withOutput(key, new Text("gfedcba,decgfba,fedgcba,gcbfeda")) //验证是否按此格式输出
.runTest();
}
}
第四步:将项目编译和打包为Anagram.jar,使用客户端将 Anagram.jar上传至hadoop的/home/hadoop/Temp目录下。

第五步:使用cd /home/hadoop/Temp 切换到当前目录,通过hadoop jar Anagram.jar com.hadoop.base.Anagram /anagram/anagram.txt /anagram/out命令行执行任务。

第六步:任务的最终结果输出到 HDFS ,使用hadoop fs -cat /anagram/out/part-r-00000命令查看结果。

标签:extend rabl int ima key 单元测试 使用 highlight cer
原文地址:https://www.cnblogs.com/zhoupp/p/10924952.html