根据快照名称读取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. [CSP-S模拟测试]:凉宫春日的忧郁(乱搞)

    题目传送门(内部题101) 输入格式 第一行输入一个整数$T$,表示数据组数. 接下来$T$行,每行两个数$X,Y$,表示$T$组数据. 输出格式 输出共有$T$行,对于每一组数据,如果$X^Y\le ...

  2. C++入门经典-例8.5-多重继承

    1:C++允许子类从多个父类继承公有的和受保护的成员,这称为多重继承. 2:多重继承的定义.多重继承有多个基类名称标识符,其声明形式如下: class 派生类名标识符:[继承方式] 基类名标识符1,. ...

  3. websphere启动报:Could not resolve placeholder 'hibernate.hbm2ddl.auto' in string value "${hibernate.hbm2ddl.auto}"

    websphere启动报/WEB-INF/applicationContext-orm- hibernate.xml]: Could not resolve placeholder 'hibernat ...

  4. Python做域用户验证登录

    安装包 ldap3 代码: from ldap3 import Server, Connection, ALL, NTLM # 连接 server = Server('public.ad.com', ...

  5. [Java]算术表达式组建二叉树,再由二叉树得到算式的后序和中序表达式

    Entry类: package com.hy; import java.io.BufferedReader; import java.io.IOException; import java.io.In ...

  6. [spring]AOP(切面)编程

    AOP 即 Aspect Oriented Program 面向切面编程 首先,在面向切面编程的思想里面,把功能分为核心业务功能,和周边功能. 所谓的核心业务,比如登陆,增加数据,删除数据都叫核心业务 ...

  7. Monkeyrunner 使用说明

    monkeyrunner为android系统新公开的一个测试工具.有助于开发人员通过脚本部署较大规模的自动化测试. Monkeyrunner       本文档中包含 一个简单的monkeyrunne ...

  8. 用泛型方法Java从实体中提取属性值,以及在泛型方法中的使用

    public <T> T getFieldValue(Object target, String fieldName, Class<T> typeName) { try { O ...

  9. jQuery页面加载完毕事件及jQuery与JavaScript的比较

    1.jQuery概述 jQuery是一个JavaScript库,它集成了JavaScript.DOM.CSS和Ajax,简化了JavaScript编程,提倡write less, do more. 2 ...

  10. 083. Remove Duplicates from Sorted List

    题目链接:https://leetcode.com/problems/rotate-list/description/ Given a sorted linked list, delete all d ...