MapReduce之日志清洗和系统计数器-12

原数据共14620行

需求:每行以空格为间隔,去除长度不足11的行,并且记录不足11,和够11的各多少次.

mapper  context.getCounter("map", "true").increment(1);  计数器,最终会打印到控制台,map和true两个参数字符串可以随便起.就是一个标识作用.

package com.buba.mapreduce.weblog;

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class WebLogMapper extends Mapper<LongWritable, Text, Text, NullWritable>{
	@Override
	protected void map(LongWritable key, Text value, Context context)
			throws IOException, InterruptedException {
		
		// 1 获取一行
		String line = value.toString();
		
		// 2 解析日志的方法
		boolean result = parseLog(line, context);
			
		// 3 判断是否合法
		if (!result) {
			return;
		}
		
		// 4合法的日志写出去
		context.write(value, NullWritable.get());
	}

	private boolean parseLog(String line, Context context) {
		// 1 截取
		String[] fields = line.split(" ");
		
		// 2 判断字段长度是否大于11
		if (fields.length > 11) {// 认为是合法的
			// 3 记录合法次数
			context.getCounter("map", "true").increment(1);
			
			return true;
		}else {// 认为是非法的
			// 4 记录不合法的次数
			
			context.getCounter("map", "false").increment(1);
			return false;
		}
	}
}

 driver

package com.buba.mapreduce.weblog;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class WebLogDriver {

	public static void main(String[] args) throws Exception {
		// 1 获取job信息
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);

		// 2 加载jar包
		job.setJarByClass(WebLogDriver.class);

		// 3 关联map
		job.setMapperClass(WebLogMapper.class);

		// 4 设置最终输出类型
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(NullWritable.class);

		// 5 设置输入和输出路径
		FileInputFormat.setInputPaths(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));

		// 6 提交
		job.waitForCompletion(true);
	}
}

猜你喜欢

转载自blog.csdn.net/kxj19980524/article/details/89354657