设计文本日志内容查找程序(假设文本日志文件有几个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);
}
}