通过mapreduce向Hbase写数据

1.

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.mapred.TableMapReduceUtil;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.lib.NullOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;


public class LoadToHBase extends Configured implements Tool{
    public static class XMap extends MapReduceBase implements Mapper{
        private JobConf conf;
        
        @Override
        public void configure(JobConf conf){
            this.conf = conf;
            try{
                this.table = new HTable(new HBaseConfiguration(conf), "observations");
            }catch(IOException e){
                throw new RuntimeException("Failed HTable construction", e);
            }
        }
        
        @Override
        public void close() throws IOException{
            super.close();
            table.close();
        }
        
        private HTable table;
        public void map(LongWritable key, Text value, OutputCollector output, Reporter reporter) throws IOException{
            String[] valuelist = value.toString().split("\t"); 
            String uid = valuelist[0];
            byte[] rowKey = uid.getBytes();
            Put p = new Put(rowKey);
            p.add("content".getBytes(), "attr1".getBytes(), "testvalue".getBytes());
            table.put(p);
          
    }
   
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        int exitCode = ToolRunner.run(new HBaseConfiguration(), new LoadToHBase(), args);
        System.exit(exitCode);
    }

    @Override
    public int run(String[] args) throws Exception {
        // TODO Auto-generated method stub
        JobConf conf = new JobConf(getClass());
        TableMapReduceUtil.addDependencyJars(conf);
        FileInputFormat.addInputPath(conf, new Path(args[0]));
        conf.setJobName("LoadToHBase");
        conf.setJarByClass(XMap.class);
        conf.setMapperClass(XMap.class);
        conf.setNumReduceTasks(0);
        conf.setOutputFormat(NullOutputFormat.class);
        JobClient.runJob(conf);
        return 0;
    }

2. 新API

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;


import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase. mapreduce.TableMapReduceUtil;

// 通过新API载入HBASE数据
public class NewLoadToHBase {
      // Map内部类
      public static class Map extends Mapper{
           
            private Configuration conf = null;
            private HTable table = null;
             
            @Override
            protected void setup(Context context)throws IOException, InterruptedException{
                  super.setup(context);
                  conf = context.getConfiguration(); // 在map任务执行前将conf设置好
                  HBaseConfiguration. addHbaseResources(conf); // 重要!没有会出现 java.io.IOException: Unable to determine ZooKeeper ensemble
                  try{
                        this.table = new HTable(conf , "observations"); // 构建HBase中的表对象,向这个表中载入数据

                  }catch(IOException e){
                        throw new RuntimeException("Failed HTable construction", e);
                  }
            }
             
            // 在map任务执行结束时,释放相关资源
            @Override
            protected void cleanup(Context context) throws IOException, InterruptedException{
                  super.cleanup(context);
                  table.close();
            }
             
            // 以下是map方法,主要完成 数据的处理,并写入HBase
            public void map(LongWritable key, Text value, Context context) throws IOException{

                  String[] valuelist = value.toString().split("\t");  
                  String uid = valuelist[0];
                  byte[] rowKey = uid.getBytes();
                  Put p = new Put(rowKey);
                  p.add("content".getBytes(), "attr1".getBytes(), "testvalue".getBytes());
                  table.put(p);
            }
      }
       
      public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
            Configuration conf = new Configuration();
            String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
            if(otherArgs.length != 1){
                  System.err.println("Usage: wordcount ");
                  System.exit(2);
            }
             
            Job job = new Job(conf, "NewLoadToHBase!");
            TableMapReduceUtil. addDependencyJars(job);
            job.setJarByClass( NewLoadToHBase.class);
            job.setMapperClass(Map.class);
            job.setNumReduceTasks(0);
            job.setInputFormatClass( TextInputFormat.class);
            job.setOutputFormatClass( NullOutputFormat.class);
            FileInputFormat.addInputPath( job, new Path(otherArgs[0]));
            System.exit(job. waitForCompletion(true) ? 0 : 1);
      }

}
参考: https://groups.google.com/forum/?fromgroups=#!topic/hadoopors/V_woQid4FYc


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值