Hbase数据批量入库实战流程

如果有大批数据要入库Hbase,普通的方法速度较慢,可以用Hbase手册里BulkLoad的方法,大致流程如下。

先说明运行环境,使用的hadoop系统是由1个主机,3个从机组成,本人使用windows远程操作。

1、将原数据文件上传主服务器。

2、通过命令将该数据文件导入HDFS。命令如下:

hadoop dfs -copyFromLocal InputPath hdfsPath

3、编写一个MapReduce Job,主要任务是将文本数据文件转换为Hfile,代码如下:

	protected void map(LongWritable key, Text value, Context context)
			throws IOException, InterruptedException {
		String[] values = value.toString().split("\\|");
		byte[] rowKey = Bytes.toBytes(values[0]);
		for (int i = 0; i < count; i++) {
			if (values[i + 1].equals("")) {
				values[i + 1] = "$null$";
			}
			ImmutableBytesWritable rKey = new ImmutableBytesWritable(rowKey);
			KeyValue kv = new KeyValue(rowKey, Bytes.toBytes("fam1"),
					Bytes.toBytes(columnNames[i]), Bytes.toBytes(values[i + 1]));
			System.out.println("dsadsa" + values[i + 1]);
			context.write(rKey, kv);
		}
	}

public class MyDriver {
	public static void main(String[] args) throws Exception {
		Configuration conf = HBaseConfiguration.create();
		Job job = new Job(conf, "toHFile");
		job.setJarByClass(MyDriver.class);
		job.setMapperClass(MyMapper.class);
		job.setReducerClass(KeyValueSortReducer.class);
		job.setMapOutputKeyClass(ImmutableBytesWritable.class);
		job.setMapOutputValueClass(KeyValue.class);
		job.setOutputKeyClass(ImmutableBytesWritable.class);
		job.setOutputValueClass(KeyValue.class);
		
		job.setInputFormatClass(TextInputFormat.class);
		job.setOutputFormatClass(HFileOutputFormat.class);
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
}

上传jar包到服务器,命令行运行jar包:
hadoop jar ****.jar InputPath OutputPath

查看HDFS里是否有相应文件生成。

4、在Hbase里创建相应表以及表的family

5、在本机运行程序,将Hfile导入Hbase代码如下:

        public static void main(String[] args) throws Exception {  
            Configuration conf = HBaseConfiguration.create();  
            String hbase_xml = "D:/workspaces/eclipse_jee/HbaesTest/hbase-site.xml";
            conf.addResource(new Path(hbase_xml)); 
            byte[] TABLE = Bytes.toBytes("test");  
            HTable table = new HTable(conf, TABLE);  
            LoadIncrementalHFiles loader = new LoadIncrementalHFiles(conf);  
           loader.doBulkLoad(new Path("hdfs://192.9.200.126:9000/sxb/hbaseout/"), table);  
        }  

注意远程运行需要的conf以及需要在本机添加主服务器的host。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值