mapreduce的使用

以下案例写之前需要导入jar包依赖:

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

1.单词计数案例:

  1. package com.xyz;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.Path;
  4. import org.apache.hadoop.io.IntWritable;
  5. import org.apache.hadoop.io.LongWritable;
  6. import org.apache.hadoop.io.Text;
  7. import org.apache.hadoop.mapreduce.Job;
  8. import org.apache.hadoop.mapreduce.Mapper;
  9. import org.apache.hadoop.mapreduce.Reducer;
  10. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  11. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  12. import java.io.IOException;
  13. /**
  14. * @author 小勇子start
  15. * @create 2021-10-11 16:35
  16. */
  17. public class WordCount {
  18. public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
  19. Configuration conf=new Configuration();
  20. Job job= Job.getInstance(conf);
  21. //这里是对jar包的类,map的类和reduce的类三者的映射
  22. job.setJarByClass(WordCount.class);
  23. job.setMapperClass(Map.class);
  24. job.setReducerClass(Reduce.class);
  25. //这里是对map输出的关键字和值对应类型的映射
  26. job.setMapOutputKeyClass(Text.class);
  27. job.setMapOutputValueClass(IntWritable.class);
  28. //这里是对reduce输出的关键字和值对应类型的映射
  29. job.setOutputKeyClass(Text.class);
  30. job.setOutputKeyClass(IntWritable.class);
  31. //数据输入路径(此处为本地测试)
  32. FileInputFormat.setInputPaths(job,new Path("C:\\Users\\小勇子\\Desktop\\大数据培训\\练习\\mapreduceTest\\src\\data\\test.txt"));
  33. //数据输出路径(此处为本地测试)
  34. FileOutputFormat.setOutputPath(job,new Path("C:\\Users\\小勇子\\Desktop\\大数据培训\\练习\\mapreduceTest\\src\\data\\out1"));
  35. boolean flag=job.waitForCompletion(true);
  36. System.exit(flag?0:1);
  37. }
  38. static class Map extends Mapper<LongWritable,Text, Text, IntWritable>{
  39. /*Text的包有很多,注意导的是:org.apache.hadoop.io.Text
  40. 在map中前两个数据类型基本固定
  41. 后两个代表着要输出的类型,如果有reduce,则以该类型发送给reduce
  42. */没有reduce则直接以该类型输出到目标
  43. @Override
  44. protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
  45. String[] str=value.toString().split(",");
  46. for (String s:str) {
  47. context.write(new Text(s),new IntWritable(1));
  48. }
  49. }
  50. }
  51. static class Reduce extends Reducer<Text,IntWritable,Text,IntWritable>{
  52. /*
  53. <Text,IntWritable,Text,IntWritable>
  54. 前两个是map发过来关键字和值的类型
  55. 后两个是reduce输出关键字和值的类型
  56. */
  57. @Override
  58. protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
  59. int len=0;
  60. for (Object s:values) {
  61. len++;
  62. }
  63. context.write(key,new IntWritable(len));
  64. }
  65. }
  66. }

2.数据清洗案例:

  1. package com.xyz2;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.Path;
  4. import org.apache.hadoop.io.LongWritable;
  5. import org.apache.hadoop.io.NullWritable;
  6. import org.apache.hadoop.io.Text;
  7. import org.apache.hadoop.mapreduce.Counter;
  8. import org.apache.hadoop.mapreduce.Job;
  9. import org.apache.hadoop.mapreduce.Mapper;
  10. import org.apache.hadoop.mapreduce.Reducer;
  11. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  12. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  13. import java.io.IOException;
  14. /**
  15. * @author 小勇子start
  16. * @create 2021-10-11 17:23
  17. */
  18. public class RepeatProcessing {
  19. public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
  20. Configuration conf=new Configuration();
  21. Job job= Job.getInstance(conf);
  22. job.setJarByClass(RepeatProcessing.class);
  23. job.setMapperClass(Map.class);
  24. job.setReducerClass(Reduce.class);
  25. job.setMapOutputValueClass(NullWritable.class);
  26. job.setMapOutputKeyClass(Text.class);
  27. job.setOutputValueClass(NullWritable.class);
  28. job.setOutputKeyClass(Text.class);
  29. //此处为本地测试
  30. FileInputFormat.setInputPaths(job,new Path("C:\\Users\\小勇子\\Desktop\\大数据培训\\练习\\mapreduceTest\\src\\data\\test2.txt"));
  31. //此处为本地测试
  32. FileOutputFormat.setOutputPath(job,new Path("C:\\Users\\小勇子\\Desktop\\大数据培训\\练习\\mapreduceTest\\src\\data\\out2"));
  33. boolean flag=job.waitForCompletion(true);
  34. long repeat=job.getCounters().findCounter(Count.repeatCount).getValue();
  35. System.out.println("重复的行数为:"+repeat);
  36. System.exit(flag?0:1);
  37. }
  38. static enum Count{//枚举计数
  39. repeatCount
  40. }
  41. static class Map extends Mapper<LongWritable, Text,Text, NullWritable>{
  42. @Override
  43. protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
  44. context.write(value,NullWritable.get());
  45. }
  46. }
  47. static class Reduce extends Reducer<Text, NullWritable,Text,NullWritable>{
  48. @Override
  49. protected void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
  50. Counter counter=context.getCounter(Count.repeatCount);
  51. int len=0;
  52. for (Object s:values) {
  53. len++;
  54. }
  55. long val= counter.getValue();
  56. val+=len-1;
  57. counter.setValue(val);
  58. context.write(key,NullWritable.get());
  59. }
  60. }
  61. }

3.topN案例:

  1. package com.xyz;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.Path;
  4. import org.apache.hadoop.io.IntWritable;
  5. import org.apache.hadoop.io.LongWritable;
  6. import org.apache.hadoop.io.Text;
  7. import org.apache.hadoop.mapreduce.Job;
  8. import org.apache.hadoop.mapreduce.Mapper;
  9. import org.apache.hadoop.mapreduce.Reducer;
  10. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  11. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  12. import java.io.IOException;
  13. import java.util.*;
  14. /**
  15. * @author 小勇子start
  16. * @create 2021-09-30 19:53
  17. */
  18. public class Task2_4 {
  19. static class TaskMap extends Mapper<LongWritable, Text, Text, Text> {
  20. @Override
  21. protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
  22. String[] line = value.toString().split(";");
  23. String filmName = line[0];//电影名称
  24. String filmType = line[6];//电影类型
  25. String[] types = filmType.split("/|、|,");
  26. for (String s : types) {
  27. s=s.trim();
  28. if (s.length() > 2) {
  29. for (int i = 2; i < s.length(); i += 2) {
  30. String newStr = s.substring(i - 2, i);
  31. context.write(new Text(newStr), new Text(filmName));
  32. }
  33. } else
  34. context.write(new Text(s), new Text(filmName));
  35. }
  36. }
  37. }
  38. static class TaskReduce extends Reducer<Text, Text, Text, IntWritable> {
  39. ArrayList<Object[]> arrayList=new ArrayList<Object[]>();
  40. @Override
  41. protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
  42. //此处用set是因为Iterable<Text> values中存储的值中有重复的电影名称,需要取不同名字的个数
  43. HashSet set=new HashSet();
  44. for (Text s : values) {
  45. set.add(s);
  46. }
  47. Object[] data={set.size(),key.toString()};
  48. arrayList.add(data);
  49. }
  50. @Override
  51. protected void cleanup(Context context) throws IOException, InterruptedException {
  52. Object[] data=arrayList.toArray();
  53. Arrays.parallelSort(data, new Comparator<Object>() {
  54. @Override
  55. public int compare(Object o1, Object o2) {
  56. Object[] o_1=(Object[]) o1;
  57. Object[] o_2=(Object[]) o2;
  58. return (int)o_2[0]-(int)o_1[0];
  59. }
  60. });
  61. for (Object d:data) {
  62. Object[] d1=(Object[]) d;
  63. context.write(new Text(d1[1].toString()),new IntWritable((int)d1[0]));
  64. }
  65. /*取前3个
  66. for (int i=0;i<3;i++) {
  67. Object[] d1=(Object[]) data[i];
  68. context.write(new Text(d1[1].toString()),new IntWritable((int)d1[0]));
  69. }
  70. */
  71. }
  72. }
  73. public static void main(String[] args) throws Exception {
  74. Configuration conf = new Configuration();
  75. Job job = Job.getInstance(conf);
  76. job.setJarByClass(Task2_4.class);
  77. job.setMapperClass(TaskMap.class);
  78. job.setReducerClass(TaskReduce.class);
  79. job.setMapOutputKeyClass(Text.class);
  80. job.setMapOutputValueClass(Text.class);
  81. job.setOutputKeyClass(Text.class);
  82. job.setOutputValueClass(IntWritable.class);
  83. FileInputFormat.setInputPaths(job, new Path("C:\\Users\\小勇子\\Desktop\\大数据培训\\练习\\作业\\7月25日晚上任务\\数据\\2-1"));
  84. FileOutputFormat.setOutputPath(job, new Path("C:\\Users\\小勇子\\Desktop\\大数据培训\\练习\\作业\\7月25日晚上任务\\数据\\2-42"));
  85. boolean flag = job.waitForCompletion(true);
  86. System.exit(flag ? 0 : 1);
  87. }
  88. }

4.join案例(自定义Writable)

  1. package com.xyz;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.Path;
  4. import org.apache.hadoop.io.*;
  5. import org.apache.hadoop.mapreduce.Job;
  6. import org.apache.hadoop.mapreduce.Mapper;
  7. import org.apache.hadoop.mapreduce.Reducer;
  8. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  9. import org.apache.hadoop.mapreduce.lib.input.FileSplit;
  10. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  11. import java.io.DataInput;
  12. import java.io.DataOutput;
  13. import java.io.IOException;
  14. /**
  15. * @author 小勇子start
  16. * @create 2021-10-12 10:32
  17. */
  18. public class JoinDemo {
  19. static class MyDataWritable implements Writable {
  20. private String flag;//标记
  21. private String data;//一行数据
  22. @Override
  23. public void write(DataOutput dataOutput) throws IOException {
  24. dataOutput.writeUTF(flag);
  25. dataOutput.writeUTF(data);
  26. }
  27. @Override
  28. public void readFields(DataInput dataInput) throws IOException {
  29. this.flag=dataInput.readUTF();
  30. this.data=dataInput.readUTF();
  31. }
  32. public String getFlag(){
  33. return flag;
  34. }
  35. public void setFlag(String flag){
  36. this.flag=flag;
  37. }
  38. public String getData() {
  39. return data;
  40. }
  41. public void setData(String data) {
  42. this.data = data;
  43. }
  44. }
  45. static class Map extends Mapper<LongWritable, Text, IntWritable,MyDataWritable>{
  46. @Override
  47. protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
  48. String[] str=value.toString().split(",");
  49. int id=Integer.valueOf(str[0]);
  50. String fileName=((FileSplit)context.getInputSplit()).getPath().getName();
  51. MyDataWritable myData=new MyDataWritable();
  52. myData.setData(value.toString());
  53. if(fileName.contains("customers"))
  54. myData.setFlag("kh");
  55. else
  56. myData.setFlag("order");
  57. context.write(new IntWritable(id),myData);
  58. }
  59. }
  60. static class Reduce extends Reducer<IntWritable,MyDataWritable,Text, NullWritable>{
  61. @Override
  62. protected void reduce(IntWritable key, Iterable<MyDataWritable> values, Context context) throws IOException, InterruptedException {
  63. String khData="";
  64. String oData="";
  65. for (MyDataWritable m:values) {
  66. if (m.getFlag().equals("kh"))
  67. khData=m.getData();
  68. else
  69. oData=m.getData();
  70. }
  71. String newData=khData+","+oData;
  72. context.write(new Text(newData),NullWritable.get());
  73. }
  74. }
  75. public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
  76. Configuration conf=new Configuration();
  77. Job job= Job.getInstance(conf);
  78. job.setJarByClass(JoinDemo.class);
  79. job.setMapperClass(Map.class);
  80. job.setReducerClass(Reduce.class);
  81. job.setMapOutputValueClass(MyDataWritable.class);
  82. job.setMapOutputKeyClass(IntWritable.class);
  83. job.setOutputValueClass(NullWritable.class);
  84. job.setOutputKeyClass(Text.class);
  85. //此处为本地测试
  86. FileInputFormat.setInputPaths(job,new Path("C:\\Users\\小勇子\\Desktop\\大数据培训\\练习\\joinDemo\\DemoOne\\join\\"));
  87. //此处为本地测试
  88. FileOutputFormat.setOutputPath(job,new Path("C:\\Users\\小勇子\\Desktop\\大数据培训\\练习\\joinDemo\\DemoOne\\join\\out1"));
  89. boolean flag=job.waitForCompletion(true);
  90. System.exit(flag?0:1);
  91. }
  92. }

5.时间日期格式化

  1. import java.text.ParseException;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. /**
  5. * @author 小勇子start
  6. * @create 2021-10-11 17:53
  7. */
  8. public class DateTimeFormat {
  9. public static void main(String[] args) throws ParseException {
  10. String dateStr="2021.09.05";
  11. SimpleDateFormat sdf=new SimpleDateFormat("yyyy.MM.dd");
  12. SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
  13. Date oldDate=sdf.parse(dateStr);
  14. String newDateStr=sdf1.format(oldDate);
  15. Date newDate=sdf1.parse(newDateStr);
  16. System.out.println(oldDate);//结果:Sun Sep 05 00:00:00 CST 2021
  17. System.out.println(newDateStr);//结果:2021-09-05
  18. System.out.println(newDate);//结果:Sun Sep 05 00:00:00 CST 2021
  19. }
  20. }

6.mapreduce项目打jar包

  1. 右键项目 Open Module Settings
  2. 找到左侧 Artifacts,点击中间的 +号,选择JAR,然后选择“”“From Module With dependicies”
  3. 选择要执行的Main方法
  4. 点击idea上面的Builde菜单,选择Builder Artifacts。然后builder即可(如果改了代码,直接点击Rebuild
  5. 打包后将jar包上传至linux中

7.运行jar包

  1. 在linux中创建一个文本文件,然后上传至hdfs中
  2. 开始运行程序: hadoop jar xxxx.jar com.xyzy.test1.MyWordDriver /xxx.txt /out1

如果你程序中输入,输出路径是写死的(即不是用的args[0]这样的方式),那么/xxx.txt 和/out1就不需要了 ;在上传后jar包所在的位置执行上述命令,否则jar包前面使用绝对路径。

mapreduce的使用的更多相关文章

  1. Mapreduce的文件和hbase共同输入

    Mapreduce的文件和hbase共同输入 package duogemap;   import java.io.IOException;   import org.apache.hadoop.co ...

  2. mapreduce多文件输出的两方法

    mapreduce多文件输出的两方法   package duogemap;   import java.io.IOException;   import org.apache.hadoop.conf ...

  3. mapreduce中一个map多个输入路径

    package duogemap; import java.io.IOException; import java.util.ArrayList; import java.util.List; imp ...

  4. Hadoop 中利用 mapreduce 读写 mysql 数据

    Hadoop 中利用 mapreduce 读写 mysql 数据   有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 pv.uv 数据,然后为了实时查询的需求,或者一些 OLAP ...

  5. [Hadoop in Action] 第5章 高阶MapReduce

    链接多个MapReduce作业 执行多个数据集的联结 生成Bloom filter   1.链接MapReduce作业   [顺序链接MapReduce作业]   mapreduce-1 | mapr ...

  6. MapReduce

    2016-12-21  16:53:49 mapred-default.xml mapreduce.input.fileinputformat.split.minsize 0 The minimum ...

  7. 使用mapreduce计算环比的实例

    最近做了一个小的mapreduce程序,主要目的是计算环比值最高的前5名,本来打算使用spark计算,可是本人目前spark还只是简单看了下,因此就先改用mapreduce计算了,今天和大家分享下这个 ...

  8. MapReduce剖析笔记之八: Map输出数据的处理类MapOutputBuffer分析

    在上一节我们分析了Child子进程启动,处理Map.Reduce任务的主要过程,但对于一些细节没有分析,这一节主要对MapOutputBuffer这个关键类进行分析. MapOutputBuffer顾 ...

  9. MapReduce剖析笔记之七:Child子进程处理Map和Reduce任务的主要流程

    在上一节我们分析了TaskTracker如何对JobTracker分配过来的任务进行初始化,并创建各类JVM启动所需的信息,最终创建JVM的整个过程,本节我们继续来看,JVM启动后,执行的是Child ...

  10. MapReduce剖析笔记之六:TaskTracker初始化任务并启动JVM过程

    在上面一节我们分析了JobTracker调用JobQueueTaskScheduler进行任务分配,JobQueueTaskScheduler又调用JobInProgress按照一定顺序查找任务的流程 ...

随机推荐

  1. 网络编程:软件开发架构、架构总结、网络编程前戏、OSI七层协议简介、OSI七层协议之物理连接层、数据链路层、网络相关专业名词、OSI七层协议之网络层

    目录 软件开发架构 架构总结 网络编程前戏 OSI七层协议简介 OSI七层协议之物理连接层 OSI七层协议之数据链路层 网络相关专业名词 OSI七层协议之网络层 OSI七层协议之传输层 软件开发架构 ...

  2. 这可能是最全的SpringBoot3新版本变化了!

    11月24号,Spring Boot 3.0 发布了第一个正式的 GA 版本,一起看看新版本到底有哪些变化. 2.7版本升级指南 官方提供了一个从 2.7 版本升级到 3.0 的指南:https:// ...

  3. 【每日一题】【快速排序过程、循环过程无=、递归参数】2022年1月16日-NC140 排序

    快速排序 对时间复杂度和空间复杂度有要求 方法1:快速排序-递归 import java.util.*; public class Solution { /** * 代码中的类名.方法名.参数名已经指 ...

  4. pandas中loc和iloc的使用细节

    1.缘由 前段时间在使用pandas库中的索引和切片的时候,突然就感觉有点懵,赋值和索引的操作总是报错. 网上的很多资料讲的也非常的浅显,而且使用起来非常不顺手. 于是我就找到很多的网上资料,然后自己 ...

  5. SQLMap入门——获取表中的字段名

    查询表名之后,查询表中的字段名 python sqlmap.py -u http://localhost/sqli-labs-master/Less-1/?id=1 -D xssplatform -T ...

  6. LeetCode HOT 100:最大子数组和

    题目:53. 最大子数组和 题目描述: 给你一个整数数组,在该数组的所有子数组中,找到一个子数组中所有元素相加和最大,返回这个最大的和.子数组就是一个数组中,由一个或几个下标连续的元素,组成的小数组, ...

  7. python 数据迁移

    Python数据库迁移 操作数据库 mysql uroot -p create database Python1031 charset=utf8; 数据迁移 from flask_migrate im ...

  8. 【Azure 云服务】为Azure云服务配置上自签名的SSL证书步骤

    问题描述 在使用Azure Cloud Service(云服务),默认的情况下都是使用的 HTTP 服务,通过 Visual Studio 2022 创建的默认 Cloud Service项目中,在S ...

  9. Spark详解(03) - Spark3.0.0运行环境安装

    Spark详解(03) - Spark3.0.0运行环境安装 Spark运行模式 Spark常见部署模式: Local模式:在本地部署单个Spark服务 所谓的Local模式,就是不需要其他任何节点资 ...

  10. rvm安装ruby

    macOS11.1 打开终端 使用下面命令查看ruby版本 rvm list known 然后安装 rvm install 2.0.0 查看ruby版本 ruby -v   系统默认使用ruby版本 ...