六、实现RetractStreamTableSink操作
import com.springk.flink.bean.StudentInfo;
import com.springk.flink.bean.StudentScoreResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.core.fs.FileSystem;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;
public class TableStreamFlinkStudentRetractTest {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment streamTableEnvironment = StreamTableEnvironment.create(env);
//source,这里使用socket连接获取数据
DataStreamSource<String> text = env.socketTextStream("127.0.0.1", 9999, "\n");
//处理输入数据流,转换为StudentInfo类型,方便后续处理
SingleOutputStreamOperator<StudentInfo> dataStreamStudent = text.flatMap(new FlatMapFunction<String, StudentInfo>() {
@Override
public void flatMap(String s, Collector<StudentInfo> collector){
System.out.println(s);
String infos[] = s.split(",");
if(StringUtils.isNotBlank(s) && infos.length==2){
StudentInfo studentInfo = new StudentInfo();
studentInfo.setName(infos[0]);
studentInfo.setSex(infos[1]);
studentInfo.setCourse(infos[2]);
studentInfo.setScore(Float.parseFloat(infos[3]));
collector.collect(studentInfo);
}
}
});
//注册dataStreamStudent流到表中,表名为:studentInfo
streamTableEnvironment.registerDataStream("studentInfo",dataStreamStudent,"name,sex,course,score");
//查询每个学生所有学科总分数 ---使用toRetractStream作为sink输出 toRetractStream
Table studentScoreTable = streamTableEnvironment.sqlQuery("select name,sum(score) as sum_total_score from studentInfo group by name");
DataStream<Tuple2<Boolean, StudentScoreResult>> studentScoreResultDataStream = streamTableEnvironment.toRetractStream(studentScoreTable,StudentScoreResult.class);
studentScoreResultDataStream.writeAsText("/Users/springk/Documents/student-sum-sink", FileSystem.WriteMode.OVERWRITE);
env.execute("studentScoreAnalyse");
}
}
命令行中输入如下:
student-sum-sink中获取内容如下:
从结果中可以看出,输出数据有修改时会写入两条数据,原有数据置为false,写入新的数据