根据快照名称读取hbase快照中的数据,在网上查了好多资料,很少有资料能够给出清晰的方案,根据自己的摸索终于实现,现将代码贴出,希望能给大家有所帮助:

public void read(org.apache.hadoop.conf.Configuration hadoopConf, Pipeline pipeline, ReaderParam readerParam, int batchSize) {
limiter = RateLimiter.create(readerParam.getFetchSize() * M_BYTE_SIZE); //用于记录读取行数
AtomicInteger totalCount = new AtomicInteger(); JobConf conf = new JobConf(hadoopConf);
String sourceRcFilePath = readerParam.getFilePath();
logger.info(String.format("Start Read Rcfile [%s].", sourceRcFilePath));
String defaultFS=String.format("hdfs://%s", readerParam.getFsdefaultname()); try {
int size = 1;
BatchData batchData;
List<Record> recordList = new ArrayList<>(batchSize); Scan scan = new Scan();
scan.setCaching(500);
scan.setCacheBlocks(false); //离线任务必须设置
conf.set(TableInputFormat.SCAN, Base64.encodeBytes(ProtobufUtil.toScan(scan).toByteArray())); //序列化
InputFormat<ImmutableBytesWritable, Result> in = new TableSnapshotInputFormat();
Path rootDir = FSUtils.getRootDir(conf);
String[] tableNameSplit = readerParam.getFileName().split(":");
String namespace_table = tableNameSplit[0]+"_"+tableNameSplit[1]; Connection conn = ConnectionFactory.createConnection(conf);
Admin admin = conn.getAdmin();
boolean tableExist = admin.tableExists(TableName.valueOf(readerParam.getFileName()));
// List<HBaseProtos.SnapshotDescription> list = admin.listSnapshots("^"+namespace_table); // TableName[] tables = admin.listTableNames();
// List<HBaseProtos.SnapshotDescription> list = admin.listSnapshots();
// for(HBaseProtos.SnapshotDescription snapshotDescription : list){
// String snapshotName = snapshotDescription.getMsg();
// String table = snapshotDescription.getTable();
// } FileSystem fs = FileSystem.get(conf);
Path rootPath = new Path(conf.get("hbase.rootdir"));
Path snapshotDir = new Path(conf.get("hbase.rootdir")+HBASE_SNAPSHOT_BASE_PATH);
snapshotDir = SnapshotDescriptionUtils.getSnapshotRootDir(new Path(conf.get("hbase.rootdir")));
FileStatus[] listStatus = fs.listStatus(snapshotDir); // HBaseProtos.SnapshotDescription snapshotDescription = SnapshotDescriptionUtils.readSnapshotInfo(fs, new Path(conf.get("hbase.rootdir")+"/.snapshots/completed"));
// Arrays.stream(listStatus).forEach(x-> System.out.println(x.getPath().toString()));
// System.out.println("-----------------------------------------"); List<String> snapshotList = new ArrayList<String>();
Arrays.stream(listStatus).filter(x-> !x.getPath().getName().startsWith(".")).forEach(x->{
String snapshotName = x.getPath().getName();
Path snapshotPath = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootPath);
try {
HBaseProtos.SnapshotDescription s = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotPath);
System.out.println("tableName:"+ s.getTable()+"\t snapshot:"+s.getName());
if (s.getTable().equalsIgnoreCase(readerParam.getFileName())){
snapshotList.add(s.getName());
}
} catch (CorruptedSnapshotException e) {
e.printStackTrace();
}
});
// List<String> snapshotList = Arrays.stream(listStatus).filter(x-> !x.getPath().getMsg().startsWith(".")).map(x -> String.valueOf(x.getPath())).filter(x -> x.contains(namespace_table)).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
snapshotList.stream().forEach(x -> System.out.println(x));
if (snapshotList.isEmpty()){
String message = String.format("读取Hbase快照信息发生异常,没有找到对应表快照,请联系系统管理员。", readerParam.getFilePath());
logger.error(message);
throw DiException.asDiException(CommonErrorCode.CONFIG_ERROR, message);
}
String snapshotName = snapshotList.stream().sorted(Comparator.reverseOrder()).findFirst().get();
String restorTmp = String.format("%s/user/%s/restoretmp/%s", conf.get("fs.defaultFS"), "di", namespace_table);
Path restorPath = new Path(restorTmp);
// Path restorPath = new Path("hdfs://RouterSit/user/di/restoretmp/ns_di_snapshot_test2");
TableSnapshotInputFormatImpl.setInput(conf, snapshotName, restorPath); List<String> columns = Arrays.asList(readerParam.getReadColumns().split(",")); //Each file as a split
InputSplit[] splits = in.getSplits(conf, 1);
for (InputSplit split : splits){ recordReader = in.getRecordReader(split, conf, Reporter.NULL);
ImmutableBytesWritable key = recordReader.createKey();
Result value = recordReader.createValue(); List<Object> recordFields;
while (start && recordReader.next(key, value)) { Record record = result2Record(value, columns);
limiter.acquire(record.getMemorySize());
recordList.add(record);
size++;
}
} } catch (Exception e) {
String message = String.format("读取Hbase快照数据发生异常,请联系系统管理员。", readerParam.getFilePath());
logger.error(message);
throw DiException.asDiException(CommonErrorCode.CONFIG_ERROR, message, e);
} finally {
stop();
} }

  

如果读取快照数据时,数据列簇使用的是lzo压缩的话,可能会遇到lzo解压缩问题,可以参照:hbase读取快照数据-lzo压缩遇到的问题

使用TableSnapshotInputFormat读取Hbase快照数据的更多相关文章

  1. Spark读取Hbase的数据

    val conf = HBaseConfiguration.create() conf.addResource(new Path("/opt/cloudera/parcels/CDH-5.4 ...

  2. hbase与hive集成:hive读取hbase中数据

    1.创建hbase jar包到hive lib目录软连接 hive需要jar包: hive-hbase-handler-0.13.1-cdh5.3.6.jar zookeeper-3.4.5-cdh5 ...

  3. hbase读取快照数据-lzo压缩遇到的问题

    1.读取hbase快照数据时报UnsatisfiedLinkError: no gplcompression in java.library.path错: 2019-09-04 17:36:07,44 ...

  4. Spark 读取HBase和SolrCloud数据

    Spark1.6.2读取SolrCloud 5.5.1 //httpmime-4.4.1.jar // solr-solrj-5.5.1.jar //spark-solr-2.2.2-20161007 ...

  5. 关于mapreducer 读取hbase数据 存入mysql的实现过程

    mapreducer编程模型是一种八股文的代码逻辑,就以用户行为分析求流存率的作为例子 1.map端来说:必须继承hadoop规定好的mapper类:在读取hbase数据时,已经有现成的接口 Tabl ...

  6. 使用MapReduce读取HBase数据存储到MySQL

    Mapper读取HBase数据 package MapReduce; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hba ...

  7. SparkSQL读取HBase数据

    这里的SparkSQL是指整合了Hive的spark-sql cli(关于SparkSQL和Hive的整合,见文章后面的参考阅读). 本质上就是通过Hive访问HBase表,具体就是通过hive-hb ...

  8. Spark 读取HBase数据

    Spark1.6.2 读取 HBase 1.2.3 //hbase-common-1.2.3.jar //hbase-protocol-1.2.3.jar //hbase-server-1.2.3.j ...

  9. Spark读取Hbase中的数据

    大家可能都知道很熟悉Spark的两种常见的数据读取方式(存放到RDD中):(1).调用parallelize函数直接从集合中获取数据,并存入RDD中:Java版本如下: JavaRDD<Inte ...

随机推荐

  1. 实现自己的SpringMVC

    一.SpringMVC的工作原理 SpringMVC流程 1.  用户发送请求至前端控制器DispatcherServlet. 2.  DispatcherServlet收到请求调用HandlerMa ...

  2. vue 打包部署到服务器上 配置nginx访问

    坑一 css,js资源引入不正确 webpack配置文件config/index.js 需要更改: 方法一 当部署到带有文件夹的项目中,这种绝对路径就会出现问题,因为把配置的static文件夹当成了根 ...

  3. [论文理解] FoveaBox: Beyond Anchor-based Object Detector

    FoveaBox: Beyond Anchor-based Object Detector Intro 本文是一篇one-stage anchor free的目标检测文章,大体检测思路为,网络分两路, ...

  4. TensorFlow 学习(6)———TensorFlow运作方式

    本部分主要涉及到TensorFlow的运作方式和主要操作 所需的代码在https://github.com/tensorflow/tensorflow/tree/master/tensorflow/e ...

  5. GitHub:Python

    ylbtech-GitHub:Python 1.返回顶部   2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部 1. https://github.com/python 2.   6 ...

  6. Linux版本

    1.内核:Linux内核Kernel目前最新稳定版 3.4  http://www.kernel.org/ 2.发行版本:是一些厂商将Linux系统内核与应用软件和文档包装起来,并提供一些安装界面和系 ...

  7. 代码实现将键盘录入的数据拷贝到当前项目下的text.txt文件中,键盘录入数据当遇到quit时就退出

    package com.looaderman.test; import java.io.FileNotFoundException; import java.io.FileOutputStream; ...

  8. 获取sql server中自增量之scope_identity(),@@Identity,IDENT_CURRENT的区别

    http://www.lmwlove.com/ac/ID480 在sql server2005,如果要获某个表最新增加的自增量,我们都知道,可以使用COPE_IDENTITY. IDENT_CURRE ...

  9. golang struct结构体初始化的几种方式

    type User struct { Id int `json:"id" orm:"auto"` // 用户名 Username string `json:&q ...

  10. 【ABAP系列】SAP ABAP如何在调试查看EXPORT/IMPORT 内存数据

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[ABAP系列]SAP ABAP如何在调试查看E ...