根据快照名称读取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. Vuex的基本原理与使用

    我们需要知道 vue 是单向数据流的方式驱动的 什么是vuex? 为什么要使用vuex ? - 多个视图依赖于同一状态. - 来自不同视图的行为需要变更同一状态. vuex 类似Redux 的状态管理 ...

  2. python3笔记二十二:正则表达式之函数

    一:学习内容 re.match函数 re.search函数 re.findall函数 二:re.match函数 需要导入包:import re 1.格式:match(pattern,string,fl ...

  3. JS基础_break跳出外层循环

    可以为循环语句创建一个label,来表示当前循环 label:循环语句 使用break语句时,可以在break后跟着一个label 这样break会结束指定的循环 outer: for(let i=0 ...

  4. Asp.Net WebAPI 通过HttpContextBase或者HttpRquest 获取请求参数

    WEBAPI中的Request是HttpRequestMessage类型,不能像Web传统那样有querystring和from 方法接收参数,而传统的HttpReqest的基类是HttpReqest ...

  5. 九、封装登录POST请求、登录后POST请求以及GET请求

    一.封装登录后POST请求以及GET请求 /** * 全局运行时环境参数管理器 */ public static Map<String, String> BASE_GLOBAL_MAP; ...

  6. OpenCV学习笔记(14)——轮廓的性质

    提取一些经常使用的对象特征 1.长宽比 边界矩形的宽高比                                       x,y,w,h = cv2.boundingRect(cnt) a ...

  7. LC 244. Shortest Word Distance II 【lock, Medium】

    Design a class which receives a list of words in the constructor, and implements a method that takes ...

  8. 阶段3 3.SpringMVC·_03.SpringMVC常用注解_7 ModelAttribute注解

    这个注解可以作用在方法上,也可以作用在参数上 演示 user里面有三个属性, 表单只提交了两个属性.缺少了date属性 date没有获取到值因为也没提交这个值. 下面返回的user对象.上面就会拿到 ...

  9. 2019.06.05 ABAP EXCEL 操作类代码 OLE方式(模板下载,excel上传,内表下载)

    一般使用标准的excel导入方法9999行,修改了标准的excel导入FM 整合出类:excel的 模板下载,excel上传,ALV内表下载功能. 在项目一开始可以SE24创建一个类来供整体开发使用, ...

  10. MySQL使用order by field()自定义排序

    MySQL的自定义排序和Oracle相比,要简单得多. 假设在表v_education的列schoolRecord中,有以下字段:'小学','初中','高中','专科','本科','硕士','博士'. ...