海量文本日志内容查找

设计文本日志内容查找程序(假设文本日志文件有几个G的大小)。
要求:

1.能有途径输入需要匹配的字符(手写文本文件程序去读、程序启动参数代入、控制台输入等 都可以)。
2.输出带有匹配信息的整行数据到文本文件。
3.效率必须够快。

首先,先讲一讲我的整个思路过程,看到好几G的字眼,我的惯性思维会想到用Hadoop,毕竟大数据的技术的出现就是为了解决海量数据。在这里我使用的是hadoop的MapReduce,基本思路:每一行是一条记录,在map函数里面分析一行是否包括搜索的匹配数据,如果包含了匹配数据就输出到文件。在这里我是提供一个外部文件,可以输入我们要查找匹配的数据。

提供一个外部文件放我们要查询的数据:
在这里插入图片描述

将日志文件log.txt上传到HDFS
在这里插入图片描述
在这里插入图片描述

主要代码:

在这里插入图片描述
源代码:

package org.apache.hadoop.examples;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Scanner;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


public class SearchLog {
	
	public static class MyMapper extends Mapper<LongWritable, Text, Text,Text>{
		
		public static Text data=new Text();
		
		public void map(LongWritable key,Text value,Context context) throws IOException, InterruptedException{
			//日志文件中的内容每一行是一条记录
			String valueStr=value.toString();
			String[] line=valueStr.split("\n");
			//通过缓冲流从文件里面读取要查找匹配的字符
			BufferedReader in=new BufferedReader(new FileReader("/home/hadoop/input.txt"));
			String c;
			String str="";
			while((c=in.readLine())!=null){
				str+=c;
			}
			//遍历每一行是否包含搜索的数据
			for (String string : line) {
				if(string.indexOf(str)!=-1){
					data.set(string);
					//将匹配到的数据写到文件中
					context.write(data, new Text(""));
				}
			}
		}
		
	}
	
	
	public static void main(String[] args) throws Exception{
		String inputPath="hdfs://master:9000/user/hadoop/yechengchao/log.txt";
		String outputPath="hdfs://master:9000/user/hadoop/yechengchao/out";
		Configuration conf=new Configuration();
		final FileSystem fileSystem=FileSystem.get(new URI(inputPath),conf);
		if(fileSystem.exists(new Path(outputPath))){
			fileSystem.delete(new Path(outputPath),true);
		}
		Job job=Job.getInstance(conf,"SearchLog");
		//设置主类
		job.setJarByClass(SearchLog.class);
		//设置Map处理类
		job.setMapperClass(MyMapper.class);
		//设置输出类型
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		//设置输入和输出目录
		FileInputFormat.addInputPath(job, new Path(inputPath));
		FileOutputFormat.setOutputPath(job, new Path(outputPath));
		
		System.exit(job.waitForCompletion(true)?0:1);
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值