当前位置:   article > 正文

MapReduce运用-案例讲解_mapreduce的应用

mapreduce的应用

MapReduceGoogle 公司开源的一项重要技术,它是一个编程模型,用以进行大数据量的计算。MapReduce 是一种简化的并行计算编程模型,它使那些没有多少并行计算经验的开发人员也可以开发并行应用程序。

  1. 模型非常方便使用,即使是对于完全没有分布式程序的程序员也是如此。它隐藏了并行计算的细节。MapReduce运行开发人员使用自己熟悉的语言进行开发。
  2. 通过MapReduce,应用程序可以在超过1000个节点的大型集群上运行,并且提供经过优化的错误容灾。

MapReduce 采用 “分而治之”思想,把对大规模数据集的操作,分发给一个主节点管理下的各个字节点共同完成,然后整合各个字节点的中间结果,得到最终的计算结果。简而言之,MapReduce 就是“分散任务,汇总结果”。

 MapReduce 编程模型

从MapReduce 自身的命名特点可以看出,MapReduce 至少由两部分组成:MapReduce。Map理解为“分发”,Reduce理解为“聚合”。用户只需要编写 map() reduce() 两个方法的逻辑,即可完成简单的分布式程序的设计。

 MapReduce 执行过程简要说明如下

  1. 读取 HDFS 文件内容,把内容中的每一行解析成一个个的<key, value>键值对。key是每行行首相对于文件起始位置的字节偏移量,value 就是具体的数据,一个文件切片对应一个 map task ,每读取一行就会调用一次 map
  2. 自定义 map 方法,编写自己的业务逻辑,对输入的<key, value>处理,转换成新的<key,value>输出作为中间结果。
  3. 为了让 reduce 可以并行处理 map 的结果,根据业务要求需要对 map 的输出进行一定的分区 对不同分区上的数据,按照 key 进行排序分组,相同 keyvalue 放到一个集合中,把分组后的数据进行归约。每个 reduce 会接收各个map中相同分区中的数据,对多个 map任务的输出,按照不同的分区通过网络 copy 到不同 reduce 节点。这个过程称为 Shuffle洗牌 ,即Shuffle就是把我们 map 中的数据分发到 reduce 中去的一个过程。
  4. 自定义 reduce 函数,编写自己的业务逻辑,对输入的<key,value>键值对进行处理,转换成新的<key,value>输出。
  5. reduce 的输出保存到新的文件中。

搭建Windows Hadoop环境

  1. 下载 HadoopOnWindows 将 解压到一个没有中文没有空格的路径 D:/devtools
  2. window 上面配置配置 hadoop 的环境变量:HADOOP_HOME,并将 %HADOOP_HOME%/bin 配置到 Path 中
  3. hadoop 文件 bin 目录下的 hadoop.dll 文件放在系统盘 C:\Windows\System32 目录

Hadoop自定义数据类型

MapReduce 要求<key, value>的 keyvalue 都要实现 Writable 接口,从而支持Hadoop序列化反序列化

Java的类型

Hadoop的内置类

Java的类型

Hadoop的内置类

boolean

BooleanWritable

Float/float

FloatWritable

Integer/int

IntWritable

Double/double

DoubleWritable

Login/long

LoginWritable

String

Text

NullWritablekeyvalue 为空时使用

ArrayWritable 存储属于Writable类型的值数组

开发步骤

  1. 添加 hadoop 开发依赖 hadoop-client
  2. 继承 Mapper 类实现自己的 Mapper 类,并重写 map() 方法
  3. 继承 Reduce 类实现自己的 Reduce 类,并重写 reduce() 方法
  4. 程序主入口类编写,创建 Job 和 任务入口
  5. 配置打包插件,执行 mvn clean package 对工程进行构建
  6. 上传 jarLinudx 远程服务器任意目录,并执行程序输出到 output 目录下
  7. 查询执行后的结果

导入坐标依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.apache.hadoop</groupId>
  4. <artifactId>hadoop-client</artifactId>
  5. <version>2.7.3</version>
  6. </dependency>
  7. </dependencies>

编写Mapper业务逻辑

  1. // Mapper
  2. public static class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
  3. @Override
  4. // key --> 字符偏移量 value 文本读取的一行数据 hello world context 上下文
  5. protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
  6. // map逻辑
  7. // 获取每一行数据,转为字符串类型,通过split方法按空格进行拆分获取一个数组
  8. String[] words = value.toString().split(" ");
  9. // 遍历数组,获取每一个单词,通过上下文(context) 以 (单词,1) 的格式写到reduce中
  10. for (String word : words) {
  11. context.write(new Text(word),new IntWritable(1));
  12. }
  13. }
  14. }

编写Reduce业务逻辑

  1. // Reduce
  2. public static class WordCountReduce extends Reducer<Text,IntWritable,Text,IntWritable>{
  3. @Override
  4. protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
  5. // key hadoop value <1,1,1>
  6. int count = 0;
  7. // 遍历可迭代对象,获取数值进行统计
  8. for (IntWritable num : values) {
  9. count += num.get();
  10. }
  11. //次数计算完毕,通过上下文 context 以 (hadoop,4) 格式写到文件中
  12. context.write(key,new IntWritable(count));
  13. }
  14. }

编写MapReduce程序主类

  1. // 定义MR执行任务,关联Mapper 和 Reduce 以及 输出和输出文件地址
  2. public static void main(String[] args) throws Exception{
  3. //1. 实例化MR环境 --> Configuration
  4. Configuration conf = new Configuration();
  5. //2. 通过环境实例化一个任务 Job
  6. Job job = Job.getInstance(conf,"词频统计");
  7. //3. 指定执行任务的类是谁--> 入口方法所在的类
  8. job.setJarByClass(WordCountJob.class);
  9. // 4. 指定输入文件所在的位置
  10. // D:\WorkSpace\MapReduce\input\words.txt
  11. FileInputFormat.setInputPaths(job,new Path("D:\\WorkSpace\\MapReduce\\input\\words.txt"));
  12. // 5. 指定Mapper阶段所对应的类
  13. job.setMapperClass(WordCountMapper.class);
  14. // Text, IntWritable
  15. // 5.1 指定Mapper的输出key和value的类型
  16. job.setMapOutputKeyClass(Text.class);
  17. job.setMapOutputValueClass(IntWritable.class);
  18. // 6. 指定Reduce阶段所对应的类
  19. job.setReducerClass(WordCountReduce.class);
  20. // Text,IntWritable
  21. // 6.1 指定Reduce的输出key和value的类型
  22. job.setOutputKeyClass(Text.class);
  23. job.setOutputValueClass(IntWritable.class);
  24. // 7. 指定结果输出的地址 -->输出的地址一定不能存在
  25. // 7.1 MR程序输出路径不能存在,通过HDFS API 进行判断删除
  26. Path outputPath = new Path("D:\\WorkSpace\\MapReduce\\output");
  27. // 获取HDFS 文件系统对象
  28. FileSystem fs = FileSystem.get(conf);
  29. // 判断指定的输出地址是否存在,如果存在,则删除
  30. if(fs.exists(outputPath)){
  31. fs.delete(outputPath,true);
  32. }
  33. // 指定处理后的数据输出地址
  34. FileOutputFormat.setOutputPath(job,outputPath);
  35. // 8. 执行任务,输出成功或失败
  36. boolean flg = job.waitForCompletion(true);
  37. System.out.println(flg?"执行成功":"执行失败");
  38. // System.exit(flg?0:1);
  39. }

MR程序打成JAR包,Hadoop平台运行

添加打JAR包插件,并指定入口类

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.apache.maven.plugins</groupId>
  5. <artifactId>maven-jar-plugin</artifactId>
  6. <version>2.4</version>
  7. <configuration>
  8. <archive>
  9. <manifest>
  10. <!--改成自己的MR程序main方法所在的类全路径-->
  11. <mainClass>org.example.mapreduce.WordCountJob</mainClass>
  12. </manifest>
  13. </archive>
  14. </configuration>
  15. </plugin>
  16. </plugins>
  17. </build>

修改MapReduce程序,动态指定输入输出路径

  1. public static void main(String[] args) throws Exception{
  2. if(args.length<2){
  3. System.err.println("Usage: yarn jar <jar_name> <in_path> <out_path>");
  4. System.exit(2);
  5. }
  6. FileInputFormat.setInputPaths(job,args[0]);
  7. FileOutputFormat.setOutputPath(job,args[1]);
  8. }

通过Maven插件进行打JAR

  1. 执行 mvn clean package 对工程进行构建
  2. 注意:词频统计的输入地址和输出地址都是HDFS文件系统地址。
[cdhong@centos8 hadoop]$ yarn jar mapreduce-demo-1.0-SNAPSHOT.jar /input/words.txt /output

使用IDEA直接交互Hadoop环境

  1. Configuration conf = new Configuration();
  2. conf.set("fs.defaultFS","hdfs://node:9000"); // 执行操作的Hadoop环境,默认是本地
  3. System.setProperty("HADOOP_USER_NAME","root"); // 指定操作的用户

数据去重

MapReduce流程中,Map的输出<key, value>经过 Shuffle 过程聚集成 <key, value-list> 后会交给Reduce。当Reduce接收到一个<key, value_list>时就直接将key复制到输出key中,并将value设置为空值。Reduce中的key表示要统计的数据,value则没有太大意义。

  1. 片名:我不是药神,主演:徐峥,上映时间:2018-07-05,9.6
  2. 片名:千与千寻,主演:周冬雨, 上映时间:2019-06-21,评分:9.3
  3. 片名:阿甘正传,主演:汤姆·汉克斯, 上映时间:1994-07-06,评分:9.4
  4. 片名:阿甘正传,主演:汤姆·汉克斯, 上映时间:1994-07-06,评分:9.4
  5. 片名:触不可及,主演:弗朗索瓦·克鲁塞, 上映时间:2011-11-02,评分:9.1
  6. 片名:楚门的世界,主演:金·凯瑞, 上映时间:1998,评分:8.9
  7. 片名:寻梦环游记,主演:安东尼·冈萨雷斯,上映时间:2017-11-24,评分:9.6
  8. 片名:我不是药神,主演:徐峥,上映时间:2018-07-05,9.6
  9. 片名:楚门的世界,主演:金·凯瑞, 上映时间:1998,评分:8.9
  1. public class RepeatHandler {
  2. public static class RepeatHandlerMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
  3. @Override
  4. protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
  5. context.write(value, NullWritable.get());
  6. }
  7. }
  8. public static class RepeatHandlerReduce extends Reducer<Text, NullWritable, Text, NullWritable> {
  9. @Override
  10. protected void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
  11. context.write(key, NullWritable.get());
  12. }
  13. }
  14. public static void main(String[] args) throws Exception {
  15. Configuration conf = new Configuration();
  16. Job job = Job.getInstance(conf);
  17. job.setJarByClass(RepeatHandler.class);
  18. // 设置Mapper
  19. job.setMapperClass(RepeatHandlerMapper.class);
  20. job.setMapOutputKeyClass(Text.class);
  21. job.setMapOutputValueClass(NullWritable.class);
  22. // 设置Reduce
  23. job.setReducerClass(RepeatHandlerReduce.class);
  24. job.setOutputKeyClass(Text.class);
  25. job.setOutputValueClass(NullWritable.class);
  26. // 设置输入和输出目录
  27. FileInputFormat.setInputPaths(job, new Path("E:\\WorkSpace\\mapreduce\\input\\*"));
  28. Path path = new Path("E:\\WorkSpace\\mapreduce\\output");
  29. FileSystem fileSystem = FileSystem.get(conf);
  30. if (fileSystem.exists(path)) {
  31. fileSystem.delete(path, true);
  32. }
  33. FileOutputFormat.setOutputPath(job, path);
  34. // 任务执行
  35. System.exit(job.waitForCompletion(true) ? 0 : 1);
  36. }
  37. }

统计各部门员工薪水总和

  1. 7369,SMITH,CLERK,7902,1980/12/17,800,,20
  2. 7499,ALLEN,SALESMAN,7698,1981/2/20,1600,300,30
  3. 7521,WARD,SALESMAN,7698,1981/2/22,1250,500,30
  4. 7566,JONES,MANAGER,7839,1981/4/2,2975,,20
  5. 7654,MARTIN,SALESMAN,7698,1981/9/28,1250,1400,30
  6. 7698,BLAKE,MANAGER,7839,1981/5/1,2850,,30
  7. 7782,CLARK,MANAGER,7839,1981/6/9,2450,,10
  8. 7788,SCOTT,ANALYST,7566,1987/4/19,3000,,20
  9. 7839,KING,PRESIDENT,,1981/11/17,5000,,10
  10. 7844,TURNER,SALESMAN,7698,1981/9/8,1500,0,30
  11. 7876,ADAMS,CLERK,7788,1987/5/23,1100,,20
  12. 7900,JAMES,CLERK,7698,1981/12/3,950,,30
  13. 7902,FORD,ANALYST,7566,1981/12/3,3000,,20
  14. 7934,MILLER,CLERK,7782,1982/1/23,1300,,10
  1. public class SalaryTotalHandler {
  2. public static class SalaryTotalHandlerMapper extends Mapper<LongWritable, Text, IntWritable, DoubleWritable>{
  3. @Override
  4. protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
  5. String[] line = value.toString().split(",");
  6. int deptNo = Integer.parseInt(line[7]); // 部门编号
  7. double salary = Double.parseDouble(line[5]); // 薪资
  8. context.write(new IntWritable(deptNo),new DoubleWritable(salary));
  9. }
  10. }
  11. public static class SalaryTotalHandlerReduce extends Reducer<IntWritable, DoubleWritable,IntWritable, DoubleWritable>{
  12. @Override
  13. protected void reduce(IntWritable key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException {
  14. // 对总工资求和
  15. double total = 0;
  16. for (DoubleWritable value : values) {
  17. total += value.get();
  18. }
  19. context.write(key,new DoubleWritable(total));
  20. }
  21. }
  22. }

统计各部门员工总数,平均薪资,总薪资???

多表查询

采用 MapReduce 实现类似下面 SQL 语句的功能: select d.*,e.* from emp e join dept d on e.deptno=d.deptno;

  1. Map 端读取所有的文件,并为输出的内容加上标识,代表文件数据来源于员工表还是部门表,获取连接字段作为key,进行分组。
  2. Reduce 端,获取每个分组中带有标识的数据与无标识的数据进行拼接即可。
  1. 10,ACCOUNTING,NEW YORK
  2. 20,RESEARCH,DALLAS
  3. 30,SALES,CHICAGO
  4. 40,OPERATIONS,BOSTON
  1. public class EqualJoinHandler {
  2. public static class EqualJoinHandlerMapper extends Mapper<LongWritable, Text, Text, Text> {
  3. // 接收所有文件,对两张表打标识,根据连接列分组
  4. @Override
  5. protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
  6. String[] line = value.toString().split(","); //获取两个文件中的每一行数据,通过逗号分割获取数组
  7. String deptNo = line.length == 3 ? line[0] : line[7]; // 根据数组的长度判断分别获取对应的分组字段 deptNo
  8. context.write(new Text(deptNo), value); // 根据deptNo字段进行分组传递给Reduce
  9. }
  10. }
  11. public static class EqualJoinHandlerReduce extends Reducer<Text, Text, Text, NullWritable> {
  12. @Override
  13. protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
  14. // 数据暂存,Iterable有指针,且不方便后续处理
  15. ArrayList<String> list = new ArrayList<>();
  16. values.forEach(item -> list.add(item.toString()));
  17. // 查找部门数据,用于拼接在Emp表的后面
  18. String deptInfo = list.stream().filter(item -> item.split(",").length == 3).findFirst().orElse("");
  19. // 查找所有员工数据,把dept表的数据拼接到每个员工表数据后面
  20. list.stream()
  21. .filter(item -> item.split(",").length > 3) // 过滤部门表数据
  22. .map(item -> item.concat(deptInfo.substring(3))) // 拼接部门表数据,并去除部门编号前缀
  23. .forEach(item -> context.write(new Text(item), NullWritable.get())); // 循环写入文件中
  24. }
  25. }
  26. }

JSON数据格式化

通过 JSON 工具解析JSON字符串数据,获取所有数据维度,并按相应格式保存为数据文件

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.76</version>
  5. </dependency>

JSON数据样例

  1. {
  2. "success": true,
  3. "msg": null,
  4. "code": 0,
  5. "content": {
  6. "showId": "43e327f364c144be893e5adc4625c364",
  7. "hrInfoMap": {
  8. "7134703": {
  9. "userId": 5930479,
  10. "portrait": null,
  11. "realName": "陈小姐",
  12. "positionName": "招聘主管"
  13. },
  14. "8042425": {
  15. "userId": 10905492,
  16. "portrait": "i/image/M00/45/DA/Ciqc1F9Dj52Afz0hAACeGEp-ay0996.png",
  17. "realName": "林小姐",
  18. "positionName": "人事专员"
  19. }
  20. },
  21. "pageNo": 1,
  22. "positionResult": {
  23. "resultSize": 15,
  24. "result": [{
  25. "positionId": 8094442,
  26. "companyFullName": "上海致宇信息技术有限公司",
  27. "companyShortName": "致宇信息",
  28. "companySize": "150-500人",
  29. "industryField": "金融,软件开发",
  30. "financeStage": "不需要融资",
  31. "companyLabelList": ["股票期权", "绩效奖金", "专项奖金", "年底双薪"],
  32. "firstType": "开发|测试|运维类",
  33. "secondType": "数据开发",
  34. "thirdType": "BI工程师",
  35. "skillLables": ["数据仓库", "Hadoop", "Spark", "Hive"],
  36. "positionLables": ["数据仓库", "Hadoop", "Spark", "Hive"],
  37. "industryLables": [],
  38. "createTime": "2020-12-25 14:16:31",
  39. "formatCreateTime": "2天前发布",
  40. "city": "厦门",
  41. "district": "思明区",
  42. "businessZones": null,
  43. "salary": "18k-22k",
  44. "salaryMonth": "13",
  45. "workYear": "1-3年",
  46. "jobNature": "全职",
  47. "education": "本科",
  48. "positionAdvantage": "五险一金 年终奖 两次调薪 晋升空间",
  49. "imState": "threeDays",
  50. "lastLogin": "2020-12-25 18:17:20",
  51. "publisherId": 10876210
  52. }, {
  53. "positionId": 8136910,
  54. "positionName": "(大数据专场)Java开发工程师/专家-【数据架构】",
  55. "companyId": 1880,
  56. "companyFullName": "北京达佳互联信息技术有限公司",
  57. "companyShortName": "快手",
  58. "companyLogo": "i/image/M00/49/E7/Ciqc1F9QZJSAC0VBAACwLdjC9yo459.png",
  59. "companySize": "2000人以上",
  60. "industryField": "文娱丨内容",
  61. "financeStage": "D轮及以上",
  62. "companyLabelList": ["股票期权", "弹性工作", "定期体检", "岗位晋升"],
  63. "firstType": "开发|测试|运维类",
  64. "secondType": "后端开发",
  65. "thirdType": "Java",
  66. "skillLables": [],
  67. "positionLables": [],
  68. "industryLables": [],
  69. "createTime": "2020-12-25 19:06:35",
  70. "formatCreateTime": "2天前发布",
  71. "city": "北京",
  72. "district": "海淀区",
  73. "businessZones": ["上地"],
  74. "salary": "20k-40k",
  75. "salaryMonth": "0",
  76. "workYear": "3-5年",
  77. "jobNature": "全职",
  78. "education": "本科",
  79. "positionAdvantage": "福利多,成长快",
  80. "imState": "threeDays",
  81. "lastLogin": "2020-12-25 18:48:45",
  82. "publisherId": 11043272
  83. }],
  84. "locationInfo": {
  85. "city": null,
  86. "district": null,
  87. "businessZone": null,
  88. "isAllhotBusinessZone": false,
  89. "locationCode": null,
  90. "queryByGisCode": false
  91. }
  92. },
  93. "pageSize": 15
  94. },
  95. "resubmitToken": null,
  96. "requestId": null
  97. }

MapReduce程序代码

  1. public class LaGouJob {
  2. public static class LaGouMapper extends Mapper<LongWritable, Text,Text, NullWritable>{
  3. @Override
  4. protected void map(LongWritable key, Text line, Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {
  5. // 通过阿里巴巴的 fastJSON进行JSON数据解析
  6. JSONArray result = JSON.parseObject(line.toString())
  7. .getJSONObject("content")
  8. .getJSONObject("positionResult")
  9. .getJSONArray("result");
  10. for (Object o : result) {
  11. JSONObject obj = (JSONObject)o; // 类型转换
  12. // 获取所需维度
  13. String city = obj.getString("city");
  14. String salary = obj.getString("salary");
  15. String workYear = obj.getString("workYear");
  16. String education = obj.getString("education");
  17. // 拼接数据
  18. // 完整格式:重庆,11-22K,本科,1-3年,股票期权|绩效奖金|专项奖金|年底双薪,数据仓库|Hadoop|Spark|Hive
  19. String info = city+","+salary+","+workYear+","+education;
  20. // 写到文件中
  21. context.write(new Text(info),NullWritable.get());
  22. }
  23. }
  24. }
  25. public static void main(String[] args) throws Exception{
  26. Configuration conf = new Configuration();
  27. Job job = Job.getInstance(conf);
  28. job.setJarByClass(LaGouJob.class);
  29. job.setMapperClass(LaGouMapper.class);
  30. job.setMapOutputKeyClass(Text.class);
  31. job.setMapOutputValueClass(NullWritable.class);
  32. //文件地址
  33. FileInputFormat.setInputPaths(job,new Path("D:\\WorkSpace\\MapReduce\\input\\lagou\\*"));
  34. FileOutputFormat.setOutputPath(job, HDFSUtil.delPath(conf,"D:\\WorkSpace\\MapReduce\\output"));
  35. System.exit(job.waitForCompletion(true)?0:1);
  36. }
  37. }

序列化求每个部门的平均工资和奖金和

序列化时一种将内存中的Java对象转化为其他可存储文件或可跨计算机传输数据流的一种技术。

由于在运行程序的过程中,保存在内存中的Java对象会因为断电而丢失,或在分布式系统中,Java对象需要从一台计算机传递给其他计算机进行计算,所有Java对象需要通过某种技术转为为文件或实际可传输的数据流。这就是Java的序列化。

常见的 Java 序列化方式是实现 java.io.Serializable 接口。而Hadoop的序列化则是实现 org.apache.hadoop.io.Writable 接口,该接口包含 readFields()write() 两个方法。注意:序列化和反序列化方法的字段顺序需要保持一致

  1. @Data
  2. @Builder
  3. @NoArgsConstructor
  4. @AllArgsConstructor
  5. public class EmployeeWritable implements Writable {
  6. private int empno;
  7. private String ename;
  8. private String job;
  9. private int mgr;
  10. private String hiredate;
  11. private double sal;
  12. private double comm;
  13. private int deptno;
  14. @Override // 序列化
  15. public void write(DataOutput out) throws IOException {
  16. out.writeInt(this.empno);
  17. out.writeUTF(this.ename);
  18. out.writeUTF(this.job);
  19. out.writeInt(this.mgr);
  20. out.writeUTF(this.hiredate);
  21. out.writeDouble(this.sal);
  22. out.writeDouble(this.comm);
  23. out.writeInt(this.deptno);
  24. }
  25. @Override
  26. public void readFields(DataInput in) throws IOException {
  27. this.empno = in.readInt();
  28. this.ename = in.readUTF();
  29. this.job = in.readUTF();
  30. this.mgr = in.readInt();
  31. this.hiredate = in.readUTF();
  32. this.sal = in.readDouble();
  33. this.comm = in.readDouble();
  34. this.deptno = in.readInt();
  35. }
  36. }
  37. public class SalaryAvgHandler {
  38. public static class SalaryAvgHandlerMapper extends Mapper<LongWritable, Text, IntWritable, EmployeeWritable> {
  39. @Override
  40. protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
  41. String[] line = value.toString().split(",");
  42. EmployeeWritable emp = EmployeeWritable.builder()
  43. .deptno(Integer.parseInt(line[0]))
  44. .ename(line[1]).job(line[2])
  45. .mgr(Integer.parseInt(Objects.equals(line[3], "") ? "-1" : line[3]))
  46. .hiredate(line[4]).sal(Double.parseDouble(line[5]))
  47. .comm(Double.parseDouble(Objects.equals(line[6], "") ? "0" : line[6]))
  48. .deptno(Integer.parseInt(line[7])).build();
  49. int deptno = Integer.parseInt(line[7]);
  50. context.write(new IntWritable(deptno), emp);
  51. }
  52. }
  53. public static class SalaryAvgHandlerReduce extends Reducer<IntWritable, EmployeeWritable, IntWritable, Text> {
  54. @Override
  55. protected void reduce(IntWritable key, Iterable<EmployeeWritable> values, Context context) throws IOException, InterruptedException {
  56. int count = 0;
  57. double sumSal = 0;
  58. double sumComm = 0;
  59. for (EmployeeWritable emp : values) {
  60. count++;
  61. sumSal += emp.getSal();
  62. sumComm += emp.getComm();
  63. }
  64. String info = sumSal / count + "\t" + sumComm;
  65. context.write(key, new Text(info));
  66. }
  67. }
  68. }

WordCount TopN

Hadoop中,排序是MapReduce的灵魂,MapTaskReduceTask均会对数据按Key排序,这个操作是MR框架的默认行为,不过有的时候我们需要自己定义排序规则,具体实现有如下两种方式。

  • 借助 TreeMap 集合工具和 Reduce 的生命周期方法 cleanup 实现
  • 使用 MapReduce 的高级 API 使用多个 MapReduce 任务来完成
  1. public static class WordCountHandlerMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
  2. @Override
  3. protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
  4. String[] line = value.toString().split(" ");
  5. for (String word : line) {
  6. context.write(new Text(word), new IntWritable(1));
  7. }
  8. }
  9. }
  10. public static class WordCountHandlerReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
  11. TreeMap<Integer, String> words = new TreeMap<>((o1, o2) -> -o1.compareTo(o2));
  12. @Override
  13. protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
  14. int sum = 0;
  15. for (IntWritable value : values) {
  16. sum += value.get();
  17. }
  18. words.put(sum,key.toString());
  19. }
  20. @Override
  21. protected void cleanup(Context context) throws IOException, InterruptedException {
  22. words.entrySet().stream()
  23. .limit(3)
  24. .forEach(item-> {
  25. try {
  26. context.write(new Text(item.getValue()),new IntWritable(item.getKey()));
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. }
  30. });
  31. }
  32. }

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号