hadoop2.2.0定製mapreduce輸出到數據庫

hadoop2.2.0定製mapreduce輸出到數據庫:

這裏以redis數據庫爲例。 java

這裏的例子是,我想統計日誌文件中的某天各個小時的訪問量,日誌格式爲: redis

2014-02-10 04:52:34 127.0.0.1 xxx

咱們知道在寫mapreduce job時,要配置輸入輸出,而後編寫mapper和reducer類,hadoop默認輸出是到hdfs的文件中,例如: 數據庫

job.setOutputFormatClass(FileOutputFormat.class);

如今咱們想要將任務計算結果輸出到數據庫(redis)中,怎麼作呢?能夠繼承FileOutputFormat類,定製本身的類,看代碼: app

public class LoginLogOutputFormat<K, V> extends FileOutputFormat<K, V> {
	/**
	 * 重點也是定製一個RecordWriter類,每一條reduce處理後的記錄,咱們即可將該記錄輸出到數據庫中
	 */
	protected static class RedisRecordWriter<K, V> extends RecordWriter<K, V>{
		private Jedis jedis; //redis的client實例
		
		public RedisRecordWriter(Jedis jedis){
			this.jedis = jedis;
		}
		
		@Override
		public void write(K key, V value) throws IOException,
				InterruptedException {
			
			boolean nullKey = key == null;
			boolean nullValue = value == null;
			if (nullKey || nullValue) return;
			
			String[] sKey = key.toString().split("-");
			String outKey = sKey[0]+"-"+sKey[1]+"-"+sKey[2]+"_login_stat"; //zset key爲yyyy-MM-dd_login_stat
			jedis.zadd(outKey.getBytes("UTF-8"), -1, 
						(sKey[3]+":"+value).getBytes("UTF-8")); //zadd, 其值格式爲: 時刻:訪問量
		}

		@Override
		public void close(TaskAttemptContext context) throws IOException,
				InterruptedException {
			if (jedis != null) jedis.disconnect(); //關閉連接
		}
	}
	
	@Override
	public RecordWriter<K, V> getRecordWriter(TaskAttemptContext job)
			throws IOException, InterruptedException {
		Jedis jedis = RedisClient.newJedis(); //構建一個redis,這裏你能夠本身根據實際狀況來構建數據庫鏈接對象
		//System.out.println("構建RedisRecordWriter");
		return new RedisRecordWriter<K, V>(jedis);
	}
}
下面就是整個job實現:
public class LoginLogStatTask extends Configured implements Tool {
	public static class MyMapper extends Mapper<LongWritable, Text, Text, IntWritable>{
		@Override
		protected void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			if (value == null || "".equals(value)) return;
			// 解析value,如: 2014-02-10 04:52:34 127.0.0.1 xxx
			String[] fields = value.toString().split(" ");
			String date = fields[0];
			String time = fields[1];
			String hour = time.split(":")[0];
			String outKey = date+"-"+hour;
			context.write(new Text(outKey), new IntWritable(1));
		}
	}
	
	public static class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
		@Override
		protected void reduce(Text key, Iterable<IntWritable> values,
				Context context)
				throws IOException, InterruptedException {
			int count = 0;
			while (values.iterator().hasNext()){ //統計數量
				count ++;
				values.iterator().next(); 
			}
			context.write(key, new IntWritable(count));
		}
	}

	@Override
	public int run(String[] args) throws Exception {
		Configuration conf = getConf();
		List<Path> inputs = new ArrayList<>();
		String inputPath = args[0];
		if (inputPath.endsWith("/")){ //若是是目錄
			inputs.addAll(HdfsUtil.listFiles(inputPath, conf));
		} else{ //若是是文件
			inputs.add(new Path(inputPath));
		}
		long ts = System.currentTimeMillis();
		String jobName = "login_logs_stat_job_" + ts;
		Job job = Job.getInstance(conf, jobName);
		job.setJarByClass(LoginLogStatTask.class);
		//添加輸入文件路徑
		for (Path p : inputs){
			FileInputFormat.addInputPath(job, p);
		}
		//設置輸出路徑
		Path out = new Path(jobName + ".out"); //以jobName.out做爲輸出
		FileOutputFormat.setOutputPath(job, out);
		//設置mapper
		job.setMapperClass(MyMapper.class);
		//設置reducer
		job.setReducerClass(MyReducer.class);
		
		//設置輸入格式
		job.setInputFormatClass(TextInputFormat.class);
		//設置輸出格式
		job.setOutputFormatClass(LoginLogOutputFormat.class);
		//設置輸出key類型
		job.setOutputKeyClass(Text.class);
		//設置輸出value類型
		job.setOutputValueClass(IntWritable.class);
		job.waitForCompletion(true);
		return job.isSuccessful()?0:1;
	}
	 
	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		int res = ToolRunner.run(conf, new LoginLogStatTask(), args);
		System.exit(res);
	}

運行job後,就會在redis數據庫中有對應的key: ide

不吝指正。 oop

相關文章
相關標籤/搜索