首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >MapReduce之partition按照key值分区

MapReduce之partition按照key值分区

作者头像
静谧星空TEL
发布2021-04-27 10:33:51
发布2021-04-27 10:33:51
51300
代码可运行
举报
运行总次数:0
代码可运行

1、设置Partitioner类和reducer个数

代码语言:javascript
代码运行次数:0
运行
复制
job.setPartitionerClass(MyPartitioner.class);
job.setNumReduceTasks(3);

2、编写Partitioner类 

代码语言:javascript
代码运行次数:0
运行
复制
	/*
	 * 对mapper的结果进行分区,让多个reducer分别对多个partition文件并行处理
	 */
	private static class MyPartitioner extends Partitioner{
		
		private static int index = -1;
		private Map map = new HashMap();
		/*
		 * return:返回值为该行数据存储在第几个分区
		 * numPartitions: reduce执行的个数
		 */
		@Override
		public int getPartition(AccounterWritable key, NullWritable value, int numPartitions) {

			String currenKey = key.getAccountName();
			// 判断key是否存在
			if(map.containsKey(currenKey)) {
				return map.get(currenKey);
			}else {
				map.put(currenKey, ++index);
				return index;
			}
		}
	}

3、序列化类

代码语言:javascript
代码运行次数:0
运行
复制
package com.gxwz.entity;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.WritableComparable;
/**
 * @author com
 *
 */
public class AccounterWritable implements WritableComparable{

	private String accountName = "";
	private double orderAmount = 0D;
	
	public String getAccountName() {
		return accountName;
	}

	public void setAccountName(String accountName) {
		this.accountName = accountName;
	}

	public double getOrderAmount() {
		return orderAmount;
	}

	public void setOrderAmount(double orderAmount) {
		this.orderAmount = orderAmount;
	}

	@Override
	public String toString() {
		return accountName + "\t" + orderAmount;
	}

	@Override
	public void write(DataOutput out) throws IOException {
		out.writeUTF(this.accountName);
		out.writeDouble(this.orderAmount);
	}

	@Override
	public void readFields(DataInput in) throws IOException {
		this.accountName = in.readUTF();
		this.orderAmount = in.readDouble();
	}

	@Override
	public int compareTo(AccounterWritable o) {
		return this.getAccountName().compareTo(o.getAccountName());
	}
	
}

4、结果截图

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/10/12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档