Map端实现JOIN

概述

​ 适用于关联表中有小表的情形.

​ 使用分布式缓存,可以将小表分发到所有的map节点,这样,map节点就可以在本地对自己所读到的大表数据进行join并输出最终结果,可以大大提高join操作的并发度,加快处理速度

#### 实现步骤

先在mapper类中预先定义好小表,进行join

引入实际场景中的解决方案:一次加载数据库或者用

#####Step 1:定义Mapper

~~~java
public class MapJoinMapper extends Mapper<LongWritable,Text,Text,Text>{
private HashMap<String, String> map = new HashMap<>();

//第一件事情:将分布式缓存的小表数据读取到本地Map集合(只需要做一次)

@Override
protected void setup(Context context) throws IOException, InterruptedException {
//1:获取分布式缓存文件列表
URI[] cacheFiles = context.getCacheFiles();

//2:获取指定的分布式缓存文件的文件系统(FileSystem)
FileSystem fileSystem = FileSystem.get(cacheFiles[0], context.getConfiguration());

//3:获取文件的输入流
FSDataInputStream inputStream = fileSystem.open(new Path(cacheFiles[0]));

//4:读取文件内容, 并将数据存入Map集合
//4.1 将字节输入流转为字符缓冲流FSDataInputStream --->BufferedReader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//4.2 读取小表文件内容,以行位单位,并将读取的数据存入map集合


String line = null;
while((line = bufferedReader.readLine()) != null){
String[] split = line.split(",");

map.put(split[0], line);

}


//5:关闭流
bufferedReader.close();
fileSystem.close();


}

//第二件事情:对大表的处理业务逻辑,而且要实现大表和小表的join操作

@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
//1:从行文本数据中获取商品的id: p0001 , p0002 得到了K2
String[] split = value.toString().split(",");
String productId = split[2]; //K2

//2:在Map集合中,将商品的id作为键,获取值(商品的行文本数据) ,将value和值拼接,得到V2
String productLine = map.get(productId);
String valueLine = productLine+"\t"+value.toString(); //V2
//3:将K2和V2写入上下文中
context.write(new Text(productId), new Text(valueLine));
}
}

~~~

#####Step 2:定义主类

~~~java
public class JobMain extends Configured implements Tool{
@Override
public int run(String[] args) throws Exception {
//1:获取job对象
Job job = Job.getInstance(super.getConf(), "map_join_job");

//2:设置job对象(将小表放在分布式缓存中)
//将小表放在分布式缓存中
// DistributedCache.addCacheFile(new URI("hdfs://node01:8020/cache_file/product.txt"), super.getConf());
job.addCacheFile(new URI("hdfs://node01:8020/cache_file/product.txt"));

//第一步:设置输入类和输入的路径
job.setInputFormatClass(TextInputFormat.class);
TextInputFormat.addInputPath(job, new Path("file:///D:\\input\\map_join_input"));
//第二步:设置Mapper类和数据类型
job.setMapperClass(MapJoinMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);

//第八步:设置输出类和输出路径
job.setOutputFormatClass(TextOutputFormat.class);
TextOutputFormat.setOutputPath(job, new Path("file:///D:\\out\\map_join_out"));


//3:等待任务结束
boolean bl = job.waitForCompletion(true);
return bl ? 0 :1;
}

public static void main(String[] args) throws Exception {
Configuration configuration = new Configuration();
//启动job任务
int run = ToolRunner.run(configuration, new JobMain(), args);
System.exit(run);
}
}

posted on 2021-09-21 19:34  季昂  阅读(74)  评论(0编辑  收藏  举报