Flink连接器-批处理-读写Hbase
Flink批处理与hbase的读写
source-hbase
父类
是模仿官方写的.
import org.apache.flink.api.common.io.LocatableInputSplitAssigner;
import org.apache.flink.api.common.io.RichInputFormat;
import org.apache.flink.api.common.io.statistics.BaseStatistics;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.io.InputSplitAssigner;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @Auther WeiJiQian
* @描述
*/
public abstract class SourceHBaseInputBase<T> extends RichInputFormat<T, MyTableInputSplit>{
protected static final Logger LOG = LoggerFactory.getLogger(SourceHBaseInputBase.class);
// helper variable to decide whether the input is exhausted or not
protected boolean endReached = false;
protected transient HTable table = null;
protected transient Scan scan = null;
protected transient Connection connection = null;
/** HBase iterator wrapper. */
protected ResultScanner resultScanner = null;
protected byte[] currentRow;
protected long scannedRows;
protected ParameterTool parameterTool;
protected abstract T mapResultToOutType(Result r);
protected abstract void getScan();
protected abstract TableName getTableName();
protected void getTable() throws IOException {
org.apache.hadoop.conf.Configuration configuration;
parameterTool = PropertiesUtil.PARAMETER_TOOL;
configuration = HBaseConfiguration.create();
configuration.set(HBASE_ZOOKEEPER_QUORUM, parameterTool.get(HBASE_ZOOKEEPER_QUORUM));
configuration.set(HBASE_ZOOKEEPER_PROPERTY_CLIENTPORT, parameterTool.get(HBASE_ZOOKEEPER_PROPERTY_CLIENTPORT));
configuration.set(HBASE_RPC_TIMEOUT, parameterTool.get(HBASE_RPC_TIMEOUT));
configuration.set(HBASE_CLIENT_OPERATION_TIMEOUT, parameterTool.get(HBASE_CLIENT_OPERATION_TIMEOUT));
configuration.set(HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, parameterTool.get(HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD));
connection = ConnectionFactory.createConnection(configuration);
table = (HTable) connection.getTable(getTableName());
}
@SneakyThrows
@Override
public void configure(Configuration parameters) {
getTable();
getScan();
}
@Override
public void open(MyTableInputSplit split) throws IOException {
System.out.println("open:" + table == null);
if (table == null) {
System.out.println("open:table is null ---------");
throw new IOException("The HBase table has not been opened! " +
"This needs to be done in configure().");
}
if (scan == null) {
throw new IOException("Scan has not been initialized! " +
"This needs to be done in configure().");
}
if (split == null) {
throw new IOException("Input split is null!");
}
logSplitInfo("opening", split);
// set scan range
currentRow = split.getStartRow();
scan.setStartRow(currentRow);
scan.setStopRow(split.getEndRow());
resultScanner = table.getScanner(scan);
endReached = false;
scannedRows = 0;
}
public T nextRecord(T reuse) throws IOException {
if (resultScanner == null) {
throw new IOException("No table result scanner provided!");
}
Result res;
try {
res = resultScanner.next();
} catch (Exception e) {
resultScanner.close();
//workaround for timeout on scan
LOG.warn("Error after scan of " + scannedRows + " rows. Retry with a new scanner...", e);
scan.withStartRow(currentRow, false);
resultScanner = table.getScanner(scan);
res = resultScanner.next();
}
if (res != null) {
scannedRows++;
currentRow = res.getRow();
return mapResultToOutType(res);
}
endReached = true;
return null;
}
private void logSplitInfo(String action, MyTableInputSplit split) {
int splitId = split.getSplitNumber();
String splitStart = Bytes.toString(split.getStartRow());
String splitEnd = Bytes.toString(split.getEndRow());
String splitStartKey = splitStart.isEmpty() ? "-" : splitStart;
String splitStopKey = splitEnd.isEmpty() ? "-" : splitEnd;
String[] hostnames = split.getHostnames();
LOG.info("{} split (this={})[{}|{}|{}|{}]", action, this, splitId, hostnames, splitStartKey, splitStopKey);
}
@Override
public boolean reachedEnd() throws IOException {
return endReached;
}
@Override
public void close() throws IOException {
LOG.info("Closing split (scanned {} rows)", scannedRows);
currentRow = null;
try {
if (resultScanner != null) {
resultScanner.close();
}
} finally {
resultScanner = null;
}
}
@Override
public void closeInputFormat() throws IOException {
try {
if (connection != null) {
connection.close();
}
} finally {
connection = null;
}
try {
if (table != null) {
table.close();
}
} finally {
table = null;
}
}
@Override
public MyTableInputSplit[] createInputSplits(final int minNumSplits) throws IOException {
if (table == null) {
throw new IOException("The HBase table has not been opened! " +
"This needs to be done in configure().");
}
if (scan == null) {
throw new IOException("Scan has not been initialized! " +
"This needs to be done in configure().");
}
// Get the starting and ending row keys for every region in the currently open table
final Pair<byte[][], byte[][]> keys = table.getRegionLocator().getStartEndKeys();
if (keys == null || keys.getFirst() == null || keys.getFirst().length == 0) {
throw new IOException("Expecting at least one region.");
}
final byte[] startRow = scan.getStartRow();
final byte[] stopRow = scan.getStopRow();
final boolean scanWithNoLowerBound = startRow.length == 0;
final boolean scanWithNoUpperBound = stopRow.length == 0;
final List<MyTableInputSplit> splits = new ArrayList<MyTableInputSplit>(minNumSplits);
for (int i = 0; i < keys.getFirst().length; i++) {
final byte[] startKey = keys.getFirst()[i];
final byte[] endKey = keys.getSecond()[i];
final String regionLocation = table.getRegionLocator().getRegionLocation(startKey, false).getHostnamePort();
// Test if the given region is to be included in the InputSplit while splitting the regions of a table
if (!includeRegionInScan(startKey, endKey)) {
continue;
}
// Find the region on which the given row is being served
final String[] hosts = new String[]{regionLocation};
// Determine if regions contains keys used by the scan
boolean isLastRegion = endKey.length == 0;
if ((scanWithNoLowerBound || isLastRegion || Bytes.compareTo(startRow, endKey) < 0) &&
(scanWithNoUpperBound || Bytes.compareTo(stopRow, startKey) > 0)) {
final byte[] splitStart = scanWithNoLowerBound || Bytes.compareTo(startKey, startRow) >= 0 ? startKey : startRow;
final byte[] splitStop = (scanWithNoUpperBound || Bytes.compareTo(endKey, stopRow) <= 0)
&& !isLastRegion ? endKey : stopRow;
int id = splits.size();
final MyTableInputSplit split = new MyTableInputSplit(id, hosts, table.getName().getName(), splitStart, splitStop);
splits.add(split);
}
}
LOG.info("Created " + splits.size() + " splits");
for (MyTableInputSplit split : splits) {
logSplitInfo("created", split);
}
return splits.toArray(new MyTableInputSplit[splits.size()]);
}
/**
* Test if the given region is to be included in the scan while splitting the regions of a table.
*
* @param startKey Start key of the region
* @param endKey End key of the region
* @return true, if this region needs to be included as part of the input (default).
*/
protected boolean includeRegionInScan(final byte[] startKey, final byte[] endKey) {
return true;
}
@Override
public InputSplitAssigner getInputSplitAssigner(MyTableInputSplit[] inputSplits) {
return new LocatableInputSplitAssigner(inputSplits);
}
@Override
public BaseStatistics getStatistics(BaseStatistics cachedStatistics) {
return null;
}
}
子类
import org.apache.flink.configuration.Configuration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.BinaryPrefixComparator;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.apache.hadoop.hbase.util.Bytes;
import javax.swing.*;
import java.util.List;
import static org.apache.hadoop.hbase.filter.FilterList.Operator.MUST_PASS_ONE;
/**
* @author WeiJiQian
* @param
* @return
*/
public class SourceDaysHbase extends SourceHBaseInputBase<UsersBean> {
public SourceDaysHbase(List<String> dates){
this.dates = dates;
}
private List<String> dates;
private UsersBean usersBean = new UsersBean();
@Override
public void configure(Configuration parameters) {
super.configure(parameters);
}
@Override
protected UsersBean mapResultToOutType(Result r) {
usersBean.setPhone11(CustomizeUtils.getPhoneOfPersonaDataRowKey(Bytes.toString(r.getRow())));
usersBean.setPhone8(CustomizeUtils.getPhone8(usersBean.getPhone11()));
return usersBean;
}
@Override
protected void getScan() {
scan = new Scan();
scan.addColumn(HBaseConstant.HBASE_PERSONA_FAMILY_MONTH_DAY, HBaseConstant.HBASE_PERSONA_ACTIVITE_DATE);
}
@Override
protected TableName getTableName() {
return TableName.valueOf(parameterTool.get(HBaseConstant.HBASE_TABLE_NAME_PERSONA_DATA));
}
}
sink-hbase
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.io.OutputFormat;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.configuration.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.mortbay.util.MultiPartWriter;
import java.io.IOException;
import static com.hecaiyun.common.bean.HBaseConstant.*;
/**
* @Auther WeiJiQian
* @描述
*/
@Slf4j
public abstract class HBaseOutputFormatBase<T> implements OutputFormat<T> {
protected final String valueString = "1";
protected String date ;
protected Table table ;
protected Connection connection;
protected BufferedMutatorParams params;
protected BufferedMutator mutator;
protected org.apache.hadoop.conf.Configuration configuration;
protected ParameterTool parameterTool;
public abstract TableName getTableName();
public void configure(Configuration parameters) {
parameterTool = PropertiesUtil.PARAMETER_TOOL;
configuration = HBaseConfiguration.create();
configuration.set(HBASE_ZOOKEEPER_QUORUM, parameterTool.get(HBASE_ZOOKEEPER_QUORUM));
configuration.set(HBASE_ZOOKEEPER_PROPERTY_CLIENTPORT, parameterTool.get(HBASE_ZOOKEEPER_PROPERTY_CLIENTPORT));
configuration.set(HBASE_RPC_TIMEOUT, parameterTool.get(HBASE_RPC_TIMEOUT));
configuration.set(HBASE_CLIENT_OPERATION_TIMEOUT, parameterTool.get(HBASE_CLIENT_OPERATION_TIMEOUT));
configuration.set(HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, parameterTool.get(HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD));
}
public void open(int taskNumber, int numTasks) throws IOException {
connection = ConnectionFactory.createConnection(configuration);
table = connection.getTable(getTableName());
params = new BufferedMutatorParams(table.getName());
//设置缓存的大小 100M
params.writeBufferSize(parameterTool.getLong(HBASE_WRITEBUFFER_SIZE));
mutator = connection.getBufferedMutator(params);
}
/*
* @author WeiJiQian
* @param rowKey
* @param family
* @param colum
* @param value
* @return org.apache.hadoop.hbase.client.Put
* 描述 覆盖数据
*/
public void putData(String rowKey,byte[] family, byte[] colum,String value ) throws IOException {
Put put = new Put(Bytes.toBytes(rowKey));
put.addColumn(family,colum,Bytes.toBytes(value));
put.setDurability(Durability.SKIP_WAL);
mutator.mutate(put);
}
public void close() throws IOException {
if (mutator != null){
mutator.flush();
mutator.close();
}
if (table != null){
table.close();
}
if (connection != null){
connection.close();
}
}
}
Flink连接器-批处理-读写Hbase的更多相关文章
- Spark读写Hbase的二种方式对比
作者:Syn良子 出处:http://www.cnblogs.com/cssdongl 转载请注明出处 一.传统方式 这种方式就是常用的TableInputFormat和TableOutputForm ...
- 【原创】大叔经验分享(25)hive通过外部表读写hbase数据
在hive中创建外部表: CREATE EXTERNAL TABLE hive_hbase_table(key string, name string,desc string) STORED BY ' ...
- Spark读写HBase
Spark读写HBase示例 1.HBase shell查看表结构 hbase(main)::> desc 'SDAS_Person' Table SDAS_Person is ENABLED ...
- Flink批处理读写Hive
import org.apache.flink.table.api.*; import org.apache.flink.table.catalog.hive.HiveCatalog; /** * @ ...
- flink连接器-流处理-读写redis
写入redis resultStream.addSink(new RedisSink(FlinkUtils.getRedisSinkConfig(parameters),new MyRedisMapp ...
- Spark读写Hbase中的数据
def main(args: Array[String]) { val sparkConf = new SparkConf().setMaster("local").setAppN ...
- Spark实战之读写HBase
1 配置 1.1 开发环境: HBase:hbase-1.0.0-cdh5.4.5.tar.gz Hadoop:hadoop-2.6.0-cdh5.4.5.tar.gz ZooKeeper:zooke ...
- spark读写hbase性能对比
一.spark写入hbase hbase client以put方式封装数据,并支持逐条或批量插入.spark中内置saveAsHadoopDataset和saveAsNewAPIHadoopDatas ...
- Spark学习笔记——读写Hbase
1.首先在Hbase中建立一张表,名字为student 参考 Hbase学习笔记——基本CRUD操作 一个cell的值,取决于Row,Column family,Column Qualifier和Ti ...
随机推荐
- 分享用MathType编辑字母与数学公式的技巧
利用几何画板在Word文档中画好几何图形后,接着需要编辑字母与数学公式,这时仅依靠Word自带的公式编辑器,会发现有很多公式不能编辑,所以应该采用专业的公式编辑器MathType,下面就一起来学习用M ...
- 需要登录才能下载的文件可以用Folx下载吗
用苹果电脑的小伙伴有没有发现,有时候文件即时有下载链接也还是要先登录才能下载,那这样的文件用下载器Folx还能下载码?下面小编将在Mac系统平台上,通过一篇教程教大家利用Folx 5的密码管理来保存网 ...
- 带你了解Boom 3D的Mac版音效模式
音乐是很好的情绪抒发途径,因为音乐蕴含了很多信息,包含了很多情感,所以我们聆听不同种类的音乐的时候会产生不同的心理感受.这就是音乐的魅力,可以让人产生共鸣引发无数的思绪.为了能够更好的体会感受音乐可以 ...
- Windows 10系统运维之OpenSSH
随着PowerShell和OpenSSH的日渐成熟,在客户终端Windows居多的运维之中,使用Win32-OpenSSH和Powershell来管理一些客户机变成了相当实用的一种解决方案. Open ...
- 阿里云ECS服务器连接MongoDB
第一次接触MongoDB,第一次部署.将一些步骤整理出来,希望以后会用到,也希望能帮组到有这方面需求的小伙伴. 设备说明: 服务器为阿里云ECS服务器,网络为专有网络VPC,Mango为买的阿里云Ma ...
- PyQt(Python+Qt)学习随笔:工具箱(QToolBox)编程使用的步骤及示例代码
老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 使用toolBox开发应用时,通过Designer设计ui界面时,只能在Designer中设计too ...
- Xray高级版白嫖破解指南
啊,阿Sir,免费的还想白嫖?? 好啦好啦不开玩笑 Xray是从长亭洞鉴核心引擎中提取出的社区版漏洞扫描神器,支持主动.被动多种扫描方式,自备盲打平台.可以灵活定义 POC,功能丰富,调用简单,支持 ...
- 第 6篇 Scrum 冲刺博客
一.站立式会议 1.站立式会议照片 2.昨天已完成的工作 完成了在数据库中对商品信息的查询 职工管理页面 3.今天计划完成的工作 完成对商品信息的分析 计划分析并编写职工信息模块代码 4.工作中遇到的 ...
- Day6 Scrum 冲刺博客
一.站立式会议# 1. 会议照片 2. 工作进度+燃尽图 团队成员 昨日完成工作 今日工作计划 遇到的困难 周梓波 将方块旋转变形 添加键盘监听事件 不熟悉监听事件的操作 纪昂学 左右 ...
- 微信小程序template和组件
template主要是展示,主要是在调用的页面中定义.用import方式引入,然后去使用,通常是单独建立一个文件夹 去管理,文件夹有两个文件wxml和wxss,wxml中 可以定义多个template ...