一、背景
序列化是指将数据从内存中的对象序列化为字节流,以便在网络中传输或持久化存储。序列化在apache flink中非常重要,因为它涉及到数据传输和状态管理等关键部分。apache flink以其独特的方式来处理数据类型以及序列化,这种方式包括它自身的类型描述符、泛型类型提取以及类型序列化框架。本文将简单介绍它们背后的概念和基本原理,侧重分享在datastream、flink sql自定义函数开发中对数据类型和序列的应用,以提升任务的运行效率。
二、简单理论阐述(基于flink 1.13)
主要参考apache flink 1.13
支持的数据类型
- java tuples and scala case classes
- java pojos
- primitive types
- regular classes
- values
- hadoop writables
- special types
具体的数据类型定义在此就不详细介绍了,具体描述可以前往flink官网查看。
typeinformation
apache flink量身定制了一套序列化框架,好处就是选择自己定制的序列化框架,对类型信息了解越多,可以在早期完成类型检查,更好地选取序列化方式,进行数据布局,节省数据的存储空间,甚至直接操作二进制数据。
typeinformation类是apache flink所有类型描述符的基类,通过阅读源码,我们可以大概分成以下几种数据类型。
- basic types:所有的java类型以及包装类:void,string,date,bigdecimal,and biginteger等。
- primitive arrays以及object arrays
- composite types
- flink java tuples(flink java api的一部分):最多25个字段,不支持空字段
- scala case classes(包括scala tuples):不支持null字段
- row:具有任意数量字段并支持空字段的tuples
- pojo 类:javabeans
- auxiliary types (option,either,lists,maps,…)
- generic types:flink内部未维护的类型,这种类型通常是由kryo序列化。
我们简单看下该类的方法,核心是createserializer,获取org.apache.flink.api.common.typeutils.typeserializer,执行序列化以及反序列化方法,主要是:
- org.apache.flink.api.common.typeutils.typeserializer#serialize
- org.apache.flink.api.common.typeutils.typeserializer#deserialize(org.apache.flink.core.memory.datainputview)

何时需要数据类型获取
在apache flink中,算子间的数据类型传递是通过流处理的数据流来实现的。数据流可以在算子之间流动,每个算子对数据流进行处理并产生输出。当数据流从一个算子流向另一个算子时,数据的类型也会随之传递。apache flink使用自动类型推断机制来确定数据流中的数据类型。在算子之间传递数据时,apache flink会根据上下文自动推断数据的类型,并在运行时保证数据的类型一致性。
举个例子:新增一个kafka source,这个时候我们需要指定数据输出类型。
@experimental
public <out> datastreamsource<out> fromsource(
source<out, ?, ?> source,
watermarkstrategy<out> timestampsandwatermarks,
string sourcename,
typeinformation<out> typeinfo) {
final typeinformation<out> resolvedtypeinfo =
gettypeinfo(source, sourcename, source.class, typeinfo);
return new datastreamsource<>(
this,
checknotnull(source, "source"),
checknotnull(timestampsandwatermarks, "timestampsandwatermarks"),
checknotnull(resolvedtypeinfo),
checknotnull(sourcename));
}
那输入类型怎么不需要指定呢?可以简单看下oneinputtransformation(单输入算子的基类)类的getinputtype()方法,就是以输入算子的输出类型为输入类型的。
/** returns the {@code typeinformation} for the elements of the input. */
public typeinformation<in> getinputtype() {
return input.getoutputtype();
}
这样source的输出类型会变成下一个算子的输入。整个dag的数据类型都会传递下去。apache flink获取到数据类型后,就可以获取对应的序列化方法。
还有一种情况就是与状态后端交互的时候需要获取数据类型,特别是非jvm堆存储的后端,需要频繁的序列化以及反序列化,例如rocksdbstatebackend。
举个例子,当我们使用valuestate时需要调用以下api:
org.apache.flink.streaming.api.operators.streamingruntimecontext#getstate
@override
public <t> valuestate<t> getstate(valuestatedescriptor<t> stateproperties) {
keyedstatestore keyedstatestore = checkpreconditionsandgetkeyedstatestore(stateproperties);
stateproperties.initializeserializerunlessset(getexecutionconfig());
return keyedstatestore.getstate(stateproperties);
}
public void initializeserializerunlessset(executionconfig executionconfig) {
if (serializeratomicreference.get() == null) {
checkstate(typeinfo != null, "no serializer and no type info");
// try to instantiate and set the serializer
typeserializer<t> serializer = typeinfo.createserializer(executionconfig);
// use cas to assure the singleton
if (!serializeratomicreference.compareandset(null, serializer)) {
log.debug("someone else beat us at initializing the serializer.");
}
}
}
可以从org.apache.flink.api.common.state.statedescriptor#initializeserializerunlessset方法看出,需要通过传入的数据类型来获取具体的序列化器。来执行具体的序列化和反序列化逻辑,完成数据的交互。
数据类型的自动推断
乍一看很复杂,各个环节都需要指定数据类型。其实大部分应用场景下,我们不用关注数据的类型以及序列化方式。flink会尝试推断有关分布式计算期间交换和存储的数据类型的信息。
这里简单介绍flink类型自动推断的核心类:
org.apache.flink.api.java.typeutils.typeextractor
在数据流操作中,flink使用了泛型来指定输入和输出的类型。例如,datastream表示一个具有类型t的数据流。在代码中使用的泛型类型参数t会被typeextractor类解析和推断。在运行时,apache flink会通过调用typeextractor的静态方法来分析操作的输入和输出,并将推断出的类型信息存储在运行时的环境中。
举个例子:用的最多的flatmap算子,当我们不指定返回类型的时候,flink会调用typeextractor类自动去推断用户的类型。
public <r> singleoutputstreamoperator<r> flatmap(flatmapfunction<t, r> flatmapper) {
typeinformation<r> outtype = typeextractor.getflatmapreturntypes((flatmapfunction)this.clean(flatmapper), this.gettype(), utils.getcalllocationname(), true);
return this.flatmap(flatmapper, outtype);
}
一般看开源框架某个类的功能我都会先看类的注释,也看typeextractor的注释,大概意思这是一个对类进行反射分析的实用程序,用于确定返回的数据类型。
/**
* a utility for reflection analysis on classes, to determine the return type of implementations of
* transformation functions.
*
* <p>notes for users of this class: automatic type extraction is a hacky business that depends on a
* lot of variables such as generics, compiler, interfaces, etc. the type extraction fails regularly
* with either {@link missingtypeinfo} or hard exceptions. whenever you use methods of this class,
* make sure to provide a way to pass custom type information as a fallback.
*/
我们来看下其中一个核心的静态推断逻辑,org.apache.flink.api.java.typeutils.typeextractor#getunaryoperatorreturntype
@publicevolving
public static <in, out> typeinformation<out> getunaryoperatorreturntype(
function function,
class<?> baseclass,
int inputtypeargumentindex,
int outputtypeargumentindex,
int[] lambdaoutputtypeargumentindices,
typeinformation<in> intype,
string functionname,
boolean allowmissing) {
preconditions.checkargument(
intype == null || inputtypeargumentindex >= 0,
"input type argument index was not provided");
preconditions.checkargument(
outputtypeargumentindex >= 0, "output type argument index was not provided");
preconditions.checkargument(
lambdaoutputtypeargumentindices != null,
"indices for output type arguments within lambda not provided");
// explicit result type has highest precedence
if (function instanceof resulttypequeryable) {
return ((resulttypequeryable<out>) function).getproducedtype();
}
// perform extraction
try {
final lambdaexecutable exec;
try {
exec = checkandextractlambda(function);
} catch (typeextractionexception e) {
throw new invalidtypesexception("internal error occurred.", e);
}
if (exec != null) {
// parameters must be accessed from behind, since jvm can add additional parameters
// e.g. when using local variables inside lambda function
// paramlen is the total number of parameters of the provided lambda, it includes
// parameters added through closure
final int paramlen = exec.getparametertypes().length;
final method sam = typeextractionutils.getsingleabstractmethod(baseclass);
// number of parameters the sam of implemented interface has; the parameter indexing
// applies to this range
final int baseparameterslen = sam.getparametertypes().length;
final type output;
if (lambdaoutputtypeargumentindices.length > 0) {
output =
typeextractionutils.extracttypefromlambda(
baseclass,
exec,
lambdaoutputtypeargumentindices,
paramlen,
baseparameterslen);
} else {
output = exec.getreturntype();
typeextractionutils.validatelambdatype(baseclass, output);
}
return new typeextractor().privatecreatetypeinfo(output, intype, null);
} else {
if (intype != null) {
validateinputtype(
baseclass, function.getclass(), inputtypeargumentindex, intype);
}
return new typeextractor()
.privatecreatetypeinfo(
baseclass,
function.getclass(),
outputtypeargumentindex,
intype,
null);
}
} catch (invalidtypesexception e) {
if (allowmissing) {
return (typeinformation<out>)
new missingtypeinfo(
functionname != null ? functionname : function.tostring(), e);
} else {
throw e;
}
}
}
- 首先判断该算子是否实现了resulttypequeryable接口,本质上就是用户是否显式指定了数据类型,例如我们熟悉的kafka source就实现了该方法,当使用了jsonkeyvaluedeserializationschema,就显式指定了类型,用户自定义schema就需要自己指定。
public class kafkasource<out>
implements source<out, kafkapartitionsplit, kafkasourceenumstate>,
resulttypequeryable<out>
//deserializationschema 是需要用户自己定义的。
@override
public typeinformation<out> getproducedtype() {
return deserializationschema.getproducedtype();
}
//jsonkeyvaluedeserializationschema
@override
public typeinformation<objectnode> getproducedtype() {
return getforclass(objectnode.class);
}
- 未实现resulttypequeryable接口,就会通过反射的方法获取returntype,判断逻辑大概是从是否是java 8 lambda方法开始判断的。获取到返回类型后再通过new typeextractor()).privatecreatetypeinfo(output,intype,(typeinformation)null)封装成flink内部能识别的数据类型;大致分为2类,泛型类型变量typevariable以及非泛型类型变量。这个封装的过程也是非常重要的,推断的数据类型是flink内部封装好的类型,序列化基本都很高效,如果不是, 就会推断为generictypeinfo走kryo等序列化方式。如感兴趣,可以看下这块的源码,在此不再赘述。
通过以上的代码逻辑的阅读,我们大概能总结出以下结论:flink内部维护了很多高效的序列化方式,通常只有数据类型被推断为org.apache.flink.api.java.typeutils.generictypeinfo时我们才需要自定义序列化类型,否则性能就是灾难;或者无法推断类型的时候,例如flink sql复杂类型有时候是无法自动推断类型的,当然某些特殊的对象kryo也无法序列化,比如之前遇到过treemap无法kryo序列化 (也可能是自己姿势不对),建议在开发apache flink作业时可以养成显式指定数据类型的好习惯。
三、开发实践
flink代码作业
如何显式指定数据类型
这个简单了,几乎所有的source、keyby、算子等都暴露了指定typeinformation<out> typeinfo的构造方法,以下简单列举几个:
- source
@experimental
public <out> datastreamsource<out> fromsource(source<out, ?, ?> source, watermarkstrategy<out> timestampsandwatermarks, string sourcename, typeinformation<out> typeinfo) {
typeinformation<out> resolvedtypeinfo = this.gettypeinfo(source, sourcename, source.class, typeinfo);
return new datastreamsource(this, (source)preconditions.checknotnull(source, "source"), (watermarkstrategy)preconditions.checknotnull(timestampsandwatermarks, "timestampsandwatermarks"), (typeinformation)preconditions.checknotnull(resolvedtypeinfo), (string)preconditions.checknotnull(sourcename));
}
- map
public <r> singleoutputstreamoperator<r> map(
mapfunction<t, r> mapper, typeinformation<r> outputtype) {
return transform("map", outputtype, new streammap<>(clean(mapper)));
}
- 自定义operator
@publicevolving
public <r> singleoutputstreamoperator<r> transform(string operatorname, typeinformation<r> outtypeinfo, oneinputstreamoperator<t, r> operator) {
return this.dotransform(operatorname, outtypeinfo, simpleoperatorfactory.of(operator));
}
- keyby
public <k> keyedstream<t, k> keyby(keyselector<t, k> key, typeinformation<k> keytype) {
preconditions.checknotnull(key);
preconditions.checknotnull(keytype);
return new keyedstream(this, (keyselector)this.clean(key), keytype);
}
- 状态后端
public valuestatedescriptor(string name, typeinformation<t> typeinfo) {
super(name, typeinfo, (object)null);
}
自定义数据类型&自定义序列化器
当遇到复杂数据类型,或者需要优化任务性能时,需要自定义数据类型,以下分享几种场景以及实现代码:
- pojo类
例如大家最常用的pojo类,何为pojo类大家可以自行查询,flink对pojo类做了大量的优化,大家使用java对象最好满足pojo的规范。
举个例子,这是一个典型的pojo类:
@data
public class broadcastconfig implements serializable {
public string config_type;
public string date;
public string media_id;
public string account_id;
public string label_id;
public long start_time;
public long end_time;
public int interval;
public string msg;
public broadcastconfig() {
}
}
我们可以这样指定其数据类型,返回的数据类就是一个typeinformation<broadcastcofig>
hashmap<string, typeinformation<?>> pojofieldname = new hashmap<>();
pojofieldname.put("config_type", types.string);
pojofieldname.put("date", types.string);
pojofieldname.put("media_id", types.string);
pojofieldname.put("account_id", types.string);
pojofieldname.put("label_id", types.string);
pojofieldname.put("start_time", types.long);
pojofieldname.put("end_time", types.long);
pojofieldname.put("interval", types.int);
pojofieldname.put("msg", types.string);
return types.pojo(
broadcastconfig.class,
pojofieldname
);
如感兴趣,可以看下org.apache.flink.api.java.typeutils.runtime.pojoserializer,看flink本身对其做了哪些优化。
- 自定义typeinformation
某些特殊场景可能还需要复杂的对象,例如,需要极致的性能优化,在flink table api中数据对象传输,大部分都是binaryrowdata,效率非常高。我们在flink datastram代码作业中也想使用,怎么操作呢?这里分享一种实现方式——自定义typeinformation,当然还有更优的实现方式,这里就不介绍了。
代码实现:本质上就是继承typeinformation,实现对应的方法。核心逻辑是createserializer()方法,这里我们直接使用table api中已经实现的binaryrowdataserializer,就可以达到同flink sql相同的性能优化。
public class binaryrowdatatypeinfo extends typeinformation<binaryrowdata> {
private static final long serialversionuid = 4786289562505208256l;
private final int numfields;
private final class<binaryrowdata> clazz;
private final typeserializer<binaryrowdata> serializer;
public binaryrowdatatypeinfo(int numfields) {
this.numfields=numfields;
this.clazz=binaryrowdata.class;
serializer= new binaryrowdataserializer(numfields);
}
@override
public boolean isbasictype() {
return false;
}
@override
public boolean istupletype() {
return false;
}
@override
public int getarity() {
return numfields;
}
@override
public int gettotalfields() {
return numfields;
}
@override
public class<binaryrowdata> gettypeclass() {
return this.clazz;
}
@override
public boolean iskeytype() {
return false;
}
@override
public typeserializer<binaryrowdata> createserializer(executionconfig config) {
return serializer;
}
@override
public string tostring() {
return "binaryrowdatatypeinfo<" + clazz.getcanonicalname() + ">";
}
@override
public boolean equals(object obj) {
if (obj instanceof binaryrowdatatypeinfo) {
binaryrowdatatypeinfo that = (binaryrowdatatypeinfo) obj;
return that.canequal(this)
&& this.numfields==that.numfields;
} else {
return false;
}
}
@override
public int hashcode() {
return objects.hash(this.clazz,serializer.hashcode());
}
@override
public boolean canequal(object obj) {
return obj instanceof binaryrowdatatypeinfo;
}
}
所以这里建议apache flink代码作业开发可以尽可能使用已经优化好的数据类型,例如binaryrowdata,可以用于高性能的数据处理场景,例如在内存中进行批处理或流式处理。由于数据以二进制形式存储,可以更有效地使用内存和进行数据序列化。同时,binaryrowdata还提供了一组方法,用于访问和操作二进制数据。
- 自定义typeserializer
上面的例子只是自定义了typeinformation,当然还会遇到自定义typeserializer的场景,例如apache flink本身没有封装的数据类型。
代码实现:这里以位图存储roaring64bitmap为例,在某些特殊场景可以使用bitmap精准去重,减少存储空间。
我们需要继承typeserializer,实现其核心逻辑也是serialize() 、deserialize() 方法,可以使用roaring64bitmap自带的序列化、反序列化方法。如果你使用的复杂对象没有提供序列化方法,你也可以自己实现或者找开源的序列化器。有了自定义的typeserializer就可以在你自定义的typeinformation中调用。
public class roaring64bitmaptypeserializer extends typeserializer<roaring64bitmap> {
/**
* sharable instance of the roaring64bitmaptypeserializer.
*/
public static final roaring64bitmaptypeserializer instance = new roaring64bitmaptypeserializer();
private static final long serialversionuid = -8544079063839253971l;
@override
public boolean isimmutabletype() {
return false;
}
@override
public typeserializer<roaring64bitmap> duplicate() {
return this;
}
@override
public roaring64bitmap createinstance() {
return new roaring64bitmap();
}
@override
public roaring64bitmap copy(roaring64bitmap from) {
roaring64bitmap copiedmap = new roaring64bitmap();
from.foreach(copiedmap::addlong);
return copiedmap;
}
@override
public roaring64bitmap copy(roaring64bitmap from, roaring64bitmap reuse) {
from.foreach(reuse::addlong);
return reuse;
}
@override
public int getlength() {
return -1;
}
@override
public void serialize(roaring64bitmap record, dataoutputview target) throws ioexception {
record.serialize(target);
}
@override
public roaring64bitmap deserialize(datainputview source) throws ioexception {
roaring64bitmap navigablemap = new roaring64bitmap();
navigablemap.deserialize(source);
return navigablemap;
}
@override
public roaring64bitmap deserialize(roaring64bitmap reuse, datainputview source) throws ioexception {
reuse.deserialize(source);
return reuse;
}
@override
public void copy(datainputview source, dataoutputview target) throws ioexception {
roaring64bitmap deserialize = this.deserialize(source);
copy(deserialize);
}
@override
public boolean equals(object obj) {
if (obj == this) {
return true;
} else if (obj != null && obj.getclass() == roaring64bitmaptypeserializer.class) {
return true;
} else {
return false;
}
}
@override
public int hashcode() {
return this.getclass().hashcode();
}
@override
public typeserializersnapshot<roaring64bitmap> snapshotconfiguration() {
return new roaring64bitmaptypeserializer.roaring64bitmapserializersnapshot();
}
public static final class roaring64bitmapserializersnapshot
extends simpletypeserializersnapshot<roaring64bitmap> {
public roaring64bitmapserializersnapshot() {
super(() -> roaring64bitmaptypeserializer.instance);
}
}
}
flink sql自定义函数
如何显式指定数据类型
这里简单分享下,在自定义function开发下遇到复杂数据类型无法在accumulator 或者input、output中使用的问题,这里我们只介绍使用复杂数据对象如何指定数据类型的场景。
我们可以先看下functiondefinitionconvertrule,这是apache flink中的一个规则(rule),用于将用户自定义的函数定义转换为对应的实现。其中通过gettypeinference()方法返回用于执行对此函数定义的调用的类型推理的逻辑。
@override
public optional<rexnode> convert(callexpression call, convertcontext context) {
functiondefinition functiondefinition = call.getfunctiondefinition();
// built-in functions without implementation are handled separately
if (functiondefinition instanceof builtinfunctiondefinition) {
final builtinfunctiondefinition builtinfunction =
(builtinfunctiondefinition) functiondefinition;
if (!builtinfunction.getruntimeclass().ispresent()) {
return optional.empty();
}
}
typeinference typeinference =
functiondefinition.gettypeinference(context.getdatatypefactory());
if (typeinference.getoutputtypestrategy() == typestrategies.missing) {
return optional.empty();
}
switch (functiondefinition.getkind()) {
case scalar:
case table:
list<rexnode> args =
call.getchildren().stream()
.map(context::torexnode)
.collect(collectors.tolist());
final bridgingsqlfunction sqlfunction =
bridgingsqlfunction.of(
context.getdatatypefactory(),
context.gettypefactory(),
sqlkind.other_function,
call.getfunctionidentifier().orelse(null),
functiondefinition,
typeinference);
return optional.of(context.getrelbuilder().call(sqlfunction, args));
default:
return optional.empty();
}
}
那我们指定复杂类型也会从通过该方法实现,不多说了,直接上代码实现。
- 指定accumulatortype
这是之前写的abstractlastvaluewithretractaggfunction功能主要是为了实现具有local-global的逻辑的lastvalue,提升作业性能。
accumulator对象:lastvaluewithretractaccumulator,可以看到该对象是一个非常复杂的对象,包含5个属性,还有list<tuple2> 复杂嵌套,以及mapview等可以操作状态后端的对象,甚至有object这种通用的对象。
public static class lastvaluewithretractaccumulator {
public object lastvalue = null;
public long lastorder = null;
public list<tuple2<object, long>> retractlist = new arraylist<>();
public mapview<object, list<long>> valuetoordermap = new mapview<>();
public mapview<long, list<object>> ordertovaluemap = new mapview<>();
@override
public boolean equals(object o) {
if (this == o) {
return true;
}
if (!(o instanceof lastvaluewithretractaccumulator)) {
return false;
}
lastvaluewithretractaccumulator that = (lastvaluewithretractaccumulator) o;
return objects.equals(lastvalue, that.lastvalue)
&& objects.equals(lastorder, that.lastorder)
&& objects.equals(retractlist, that.retractlist)
&& valuetoordermap.equals(that.valuetoordermap)
&& ordertovaluemap.equals(that.ordertovaluemap)
;
}
@override
public int hashcode() {
return objects.hash(lastvalue, lastorder, valuetoordermap, ordertovaluemap, retractlist);
}
}
gettypeinference() 是functiondefinition接口的方法,而所有的用户自定义函数都实现了该接口,我们只需要重新实现下该方法就可以,以下是代码实现。
这里我们还需要用到工具类typeinference,这是flink中的一个模块,用于进行类型推断和类型推理。
可以看出我们在accumulatortypestrategy方法中传入了一个构建好的typestrategy;这里我们将lastvaluewithretractaccumulator定义为了一个structured,不同的属性定义为具体的数据类型,datatypes工具类提供了很多丰富的对象形式,还有万能的raw类型。
public typeinference gettypeinference(datatypefactory typefactory) {
return typeinference.newbuilder()
.accumulatortypestrategy(callcontext -> {
list<datatype> datatypes = callcontext.getargumentdatatypes();
datatype argdatatype;
if (datatypes.get(0)
.getlogicaltype()
.gettyperoot()
.getfamilies()
.contains(logicaltypefamily.character_string)) {
argdatatype = datatypes.string();
} else
argdatatype = datatypeutils.tointernaldatatype(datatypes.get(0));
datatype accdatatype = datatypes.structured(
lastvaluewithretractaccumulator.class,
datatypes.field("lastvalue", argdatatype.nullable()),
datatypes.field("lastorder", datatypes.bigint()),
datatypes.field("retractlist", datatypes.array(
datatypes.structured(
tuple2.class,
datatypes.field("f0", argdatatype.nullable()),
datatypes.field("f1", datatypes.bigint())
)).bridgedto(list.class)),
datatypes.field(
"valuetoordermap",
mapview.newmapviewdatatype(
argdatatype.nullable(),
datatypes.array(datatypes.bigint()).bridgedto(list.class))),
//todo:blink 使用sortedmapview 优化性能,开源使用mapview key天然字典升序,倒序遍历性能可能不佳
datatypes.field(
"ordertovaluemap",
mapview.newmapviewdatatype(
datatypes.bigint(),
datatypes.array(argdatatype.nullable()).bridgedto(list.class)))
);
return optional.of(accdatatype);
})
.build()
;
}
- 指定outputtype
这个也很简单,直接上代码实现,主要就是outputtypestrategy中传入需要输出的数据类型即可。
@override
public typeinference gettypeinference(datatypefactory typefactory) {
return typeinference.newbuilder()
.outputtypestrategy(callcontext -> {
list<datatype> datatypes = callcontext.getargumentdatatypes();
datatype argdatatype;
if (datatypes.get(0)
.getlogicaltype()
.gettyperoot()
.getfamilies()
.contains(logicaltypefamily.character_string)) {
argdatatype = datatypes.string();
} else
argdatatype = datatypeutils.tointernaldatatype(datatypes.get(0));
return optional.of(argdatatype);
})
.build()
;
}
- 指定intputtype
在此就不做介绍了,同以上类似,在inputtypestrategy方法传入定义好的typestrategy就好。
- 根据inputtype动态调整outtype或者accumulatortype
在某些场景下,我们需要让函数功能性更强,比如当我输入是bigint类型的时候,我输出bigint类型等,类似的逻辑。
大家可以发现outputtypestrategy或者 accumulatortypestrategy的入参都是 实现了 typestrategy接口的对象,并且需要实现infertype方法。在flink框架调用该方法的时候会传入一个上下文对象callcontext,提供了获取函数入参类型的api getargumentdatatypes();
代码实现:这里的逻辑是将获取到的第一个入参对象的类型指定为输出对象的类型。
.outputtypestrategy(callcontext -> {
list<datatype> datatypes = callcontext.getargumentdatatypes();
datatype argdatatype;
if (datatypes.get(0)
.getlogicaltype()
.gettyperoot()
.getfamilies()
.contains(logicaltypefamily.character_string)) {
argdatatype = datatypes.string();
} else
argdatatype = datatypeutils.tointernaldatatype(datatypes.get(0));
return optional.of(argdatatype);
}
自定义datatype
可以发现以上分享几乎都是使用的datatypes封装好的类型,比如datatypes.string()、datatypes.long()等。那如果我们需要封装一些其他对象如何操作呢?上文提到datatypes提供了一个自定义任意类型的方法。
/**
* data type of an arbitrary serialized type. this type is a black box within the table
* ecosystem and is only deserialized at the edges.
*
* <p>the raw type is an extension to the sql standard.
*
* <p>this method assumes that a {@link typeserializer} instance is present. use {@link
* #raw(class)} for automatically generating a serializer.
*
* @param clazz originating value class
* @param serializer type serializer
* @see rawtype
*/
public static <t> datatype raw(class<t> clazz, typeserializer<t> serializer) {
return new atomicdatatype(new rawtype<>(clazz, serializer));
}
我们有这样的一个场景,需要在自定义的函数中使用bitmap计算uv值,需要定义roaring64bitmap为accumulatortype,直接上代码实现。
这里的roaring64bitmaptypeserializer已经在《自定义typeserializer》小段中实现,有兴趣的同学可以往上翻翻。
public typeinference gettypeinference(datatypefactory typefactory) {
return typeinference.newbuilder()
.accumulatortypestrategy(callcontext -> {
datatype type = datatypes.raw(
roaring64bitmap.class,
roaring64bitmaptypeserializer.instance
);
return optional.of(type);
})
.outputtypestrategy(callcontext -> optional.of(datatypes.bigint()))
.build()
;
}
四、结语
本文主要简单分享了一些自身对flink类型及序列化的认识和应用实践,能力有限,不足之处欢迎指正。
引用: https://nightlies.apache.org/flink/flink-docs-release-1.13/
*文/ 木木
本文属得物技术原创,更多精彩文章请看:得物技术
未经得物技术许可严禁转载,否则依法追究法律责任!
发表评论