hadoop 的核心还是 Map-Reduce过程和 hadoop分布式文件系统

 

第一步:定义Map过程

 
  
  1. /** 
  2.  * 
  3.  * Description: 
  4.  * 
  5.  * @author charles.wang 
  6.  * @created Mar 12, 2012 1:41:57 PM 
  7.  *  
  8.  */ 
  9. public class MyMap extends Mapper<Object, Text, Text, IntWritable> { 
  10.      
  11.     private static final IntWritable one = new IntWritable(1); 
  12.     private Text word; 
  13.      
  14.      
  15.     public void map(Object key ,Text value,Context context)  
  16.             throws IOException,InterruptedException{ 
  17.          
  18.         String line=value.toString(); 
  19.         StringTokenizer tokenizer = new StringTokenizer(line); 
  20.         while(tokenizer.hasMoreTokens()){ 
  21.             word = new Text(); 
  22.             word.set(tokenizer.nextToken()); 
  23.             context.write(word, one); 
  24.         } 
  25.          
  26.     } 
  27.  

第二步: 定义 Reduce 过程

 

 
  
  1. /** 
  2.  * 
  3.  * Description: 
  4.  * 
  5.  * @author charles.wang 
  6.  * @created Mar 12, 2012 1:48:18 PM 
  7.  *  
  8.  */ 
  9. public class MyReduce extends Reducer<Text, IntWritable, Text, IntWritable> { 
  10.      
  11.     public void reduce (Text key,Iterable<IntWritable> values,Context context) 
  12.         throws IOException ,InterruptedException{ 
  13.          
  14.         int sum=0
  15.         for(IntWritable val: values){ 
  16.             sum+=val.get(); 
  17.         } 
  18.          
  19.         context.write(key, new IntWritable(sum)); 
  20.     } 
  21.  

 

编写一个Driver 来执行Map-Reduce过程

 

 
  
  1. public class MyDriver { 
  2.  
  3.     public static void main(String [] args) throws Exception{ 
  4.             
  5.         Configuration conf = new Configuration(); 
  6.         conf.set("hadoop.job.ugi""root,root123"); 
  7.          
  8.         Job job = new Job(conf,"Hello,hadoop! ^_^"); 
  9.          
  10.         job.setJarByClass(MyDriver.class); 
  11.         job.setMapOutputKeyClass(Text.class); 
  12.         job.setMapOutputValueClass(IntWritable.class); 
  13.         job.setMapperClass(MyMap.class); 
  14.         job.setCombinerClass(MyReduce.class); 
  15.         job.setReducerClass(MyReduce.class); 
  16.         job.setInputFormatClass(TextInputFormat.class); 
  17.         job.setOutputFormatClass(TextOutputFormat.class); 
  18.          
  19.         FileInputFormat.setInputPaths(job, new Path(args[0])); 
  20.         FileOutputFormat.setOutputPath(job,new Path(args[1])); 
  21.          
  22.         job.waitForCompletion(true); 
  23.     } 
  24. }