如果有大批数据要入库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。