利用MapReduce将文件内容写入Hbase表

1、把txt文件传到hdfs上

数据以tab键分隔

2、map端

public class ReadFruitFromHDFSMapper extends Mapper<LongWritable, Text, Text, Put>{
	@SuppressWarnings("deprecation")
	@Override
	protected void map(LongWritable key, Text value, Context context)
			throws IOException, InterruptedException {
		
		//从hdfs上读取数据
		String line = value.toString();
		//读取出来的每行数据使用\t 进行分割,存于 String 数组
		String[] split = line.split("\t");
		
		String rowkey=split[0];
		String name = split[1];
		String age = split[2];
		
		Put put = new Put(Bytes.toBytes(rowkey));
		
		put.add(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes(name));
		put.add(Bytes.toBytes("info"), Bytes.toBytes("age"), Bytes.toBytes(age));
		
		context.write(new Text(rowkey), put);
		
		

	}

3、reduce端

public class WriteFruitMRFromTxtReducer extends TableReducer<Text, Put, NullWritable>{
	
	@Override
	protected void reduce(Text key, Iterable<Put> values, Context context)
			throws IOException, InterruptedException {
		//读出来的每一行数据写入到 fruit_hdfs 表中
		for(Put put: values) {
			context.write(NullWritable.get(), put);
		}
	}

4、driver端

public class M {
	public static void main(String[] args) throws Exception {
		

        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","slm001");
        conf.set("hbase.zookeeper.property.clientPort","2181");
        
        //conf.set(TableOutputFormat.OUTPUT_TABLE, "student");

        Job job = Job.getInstance(conf, M.class.getSimpleName());
       // TableMapReduceUtil.addDependencyJars(job);
        
        //这个是实现在Hbase中建好的表
        TableMapReduceUtil.initTableReducerJob("student", WriteFruitMRFromTxtReducer.class, job);
        
        
        job.setJarByClass(M.class);
        job.setMapperClass(ReadFruitFromHDFSMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Put.class);
   

        FileInputFormat.addInputPath(job, new Path("hdfs://slm001:9000/slm.txt"));
        job.setOutputFormatClass(TableOutputFormat.class);
        job.waitForCompletion(true);
	}

运行结果
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值