hadoop DistributedCache缓存区
1. 使用场景
Map Join 适用于一张表十分小、一张表很大的场景
2. 解决
在 Reduce 端处理过多的表,非常容易产生数据倾斜。怎么办?在 Map 端缓存多张表,提前处理业务逻辑,这样增加 Map 端业务,减少 Reduce 端数据的压力,尽可能的减少数据倾斜。
3 code
3.1 driver中提前设置缓存
// 加载缓存数据 文件路径
job.addCacheFile(new URI("file:///D:/input/tablecache/xxx.txt"));
// 多缓存文件
job.setCacheFiles(Uri[]);
3.2 Mapper 中得setup获取缓存文件并加载到内存中
//任务开始前将 pd 数据缓存进 pdMap
@Override
protected void setup(Context context) throws IOException, InterruptedException {
//通过缓存文件得到小表数据 pd.txt
URI[] cacheFiles = context.getCacheFiles();
Path path = new Path(cacheFiles[0]);
//获取文件系统对象,并开流
FileSystem fs = FileSystem.get(context.getConfiguration());
FSDataInputStream fis = fs.open(path);
//通过包装流转换为 reader,方便按行读取
BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
//逐行读取,按行处理
String line;
while (StringUtils.isNotEmpty(line = reader.readLine())) {
//切割一行
//01 小米
String[] split = line.split("\t");
pdMap.put(split[0], split[1]);
}
//关流
IOUtils.closeStream(reader);