MapReduce是一种编程模型,用于处理和生成大数据集,HDFS(Hadoop Distributed File System)是一个分布式文件系统,用于存储大数据,下面是一个使用MapReduce将数据写入HDFS的示例:
1、我们需要创建一个Java项目,并添加Hadoop相关的依赖库,在项目的pom.xml文件中添加以下依赖:
<dependencies> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoopclient</artifactId> <version>2.7.3</version> </dependency> </dependencies>
2、编写一个MapReduce程序,实现将数据写入HDFS的功能,以下是一个简单的示例:
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; 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; import java.io.IOException; public class WriteToHDFS { public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(Object key, Text value, Context context) throws IOException, InterruptedException { String[] tokens = value.toString().split("\s+"); for (String token : tokens) { word.set(token); context.write(word, one); } } } public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> { private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "write to HDFS"); job.setJarByClass(WriteToHDFS.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
3、编译并打包Java项目,生成jar文件。
4、使用Hadoop命令行工具运行MapReduce任务,将数据写入HDFS,假设我们已经将输入数据上传到HDFS的/input
目录下,输出目录为/output
,jar文件名为writetohdfs.jar
,则运行以下命令:
hadoop jar writetohdfs.jar WriteToHDFS /input /output
5、等待任务完成,然后可以使用hadoop fs ls /output
命令查看输出目录中的内容。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/829772.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复