Flink-Table Streaming 时间属性-Event time-实践编程(五)下

针对Flink-Table Streaming 时间属性 Event time 事件属性,实践编程如下,演示编码如下:
需要依赖的公共实体类:

@Data
public class StudentInfo{
    private String name;
    private String sex;
    private String course;
    private Float score;
    private Long timestamp;
}
@Data
public class StudentScoreResult {
    public String name;
    public float sum_total_score;
}

1、在数据流到表转换,具体实现代码如下:

import javax.annotation.Nullable;

public class TableStreamFlinkStudentTimerTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        StreamTableEnvironment streamTableEnvironment = StreamTableEnvironment.create(env);
         env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
         
        DataStreamSource<String> text = env.socketTextStream("127.0.0.1", 9999, "\n");

        SingleOutputStreamOperator<StudentInfo> dataStreamStudent = text.flatMap(new FlatMapFunction<String, StudentInfo>() {
            @Override
            public void flatMap(String s, Collector<StudentInfo> collector){
                String infos[] = s.split(",");
                if(StringUtils.isNotBlank(s) && infos.length==5){
                    StudentInfo studentInfo = new StudentInfo();
                    studentInfo.setName(infos[0]);
                    studentInfo.setSex(infos[1]);
                    studentInfo.setCourse(infos[2]);
                    studentInfo.setScore(Float.parseFloat(infos[3]));
                    studentInfo.setTimestamp(Long.parseLong(infos[4]));
                    collector.collect(studentInfo);
                }
            }
        });

        //只有定义了保留水印的水印策略,才能保留数据流的水印。否则,只有表源的rowtime属性的值是相关的。
        DataStream<StudentInfo> dataStream = dataStreamStudent.assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarks<StudentInfo>() {
            private final long maxTimeLag = 5000; // 5 seconds
            @Nullable
            @Override
            public Watermark getCurrentWatermark() {
                return new Watermark(System.currentTimeMillis() - maxTimeLag);
            }
            @Override
            public long extractTimestamp(StudentInfo studentInfo, long l) {
                return studentInfo.getTimestamp();
            }
        });

        Table tableEvent = streamTableEnvironment.fromDataStream(dataStream, "name,score,timestamp.rowtime");
        Table eventResultTable = tableEvent.window(Tumble.over("2.minutes")
                                            .on("timestamp")
                                            .as("userEventActionWindow"))
                                            .groupBy("userEventActionWindow,name")
                                            .select("name,sum(score) as sum_total_score");

        DataStream<Tuple2<Boolean, StudentScoreResult>> studentScoreResultDataStream = streamTableEnvironment.toRetractStream(eventResultTable,StudentScoreResult.class);
        studentScoreResultDataStream.print();
      
        env.execute("studentScoreAnalyse");
    }
}

输入数据:
在这里插入图片描述
输出数据汇总信息:
在这里插入图片描述
2、使用TableSource,具体代码实现如下:

import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.typeutils.TypeExtractor;
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.streaming.api.functions.AssignerWithPeriodicWatermarks;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.api.Types;
import org.apache.flink.table.sources.DefinedRowtimeAttributes;
import org.apache.flink.table.sources.RowtimeAttributeDescriptor;
import org.apache.flink.table.sources.StreamTableSource;
import org.apache.flink.table.sources.tsextractors.ExistingField;
import org.apache.flink.table.sources.wmstrategies.AscendingTimestamps;
import org.apache.flink.util.Collector;

import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;

public class StudentActionSource implements  StreamTableSource<StudentInfo>, DefinedRowtimeAttributes {

    @Override
    public DataStream<StudentInfo> getDataStream(StreamExecutionEnvironment execEnv) {

        DataStreamSource<String> text = execEnv.socketTextStream("127.0.0.1", 9999, "\n");

        SingleOutputStreamOperator<StudentInfo> dataStreamStudent = text.flatMap(new FlatMapFunction<String, StudentInfo>() {
            @Override
            public void flatMap(String s, Collector<StudentInfo> collector){
                String infos[] = s.split(",");
                if(StringUtils.isNotBlank(s) && infos.length==5){
                    StudentInfo studentInfo = new StudentInfo();
                    studentInfo.setName(infos[0]);
                    studentInfo.setSex(infos[1]);
                    studentInfo.setCourse(infos[2]);
                    studentInfo.setScore(Float.parseFloat(infos[3]));
                    studentInfo.setTimestamp(Long.parseLong(infos[4]));
                    collector.collect(studentInfo);
                }
            }
        });

        //只有定义了保留水印的水印策略,才能保留数据流的水印
        DataStream<StudentInfo> dataStream = dataStreamStudent.assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarks<StudentInfo>() {
            private final long maxOutOfOrderness = 5000; // 最大允许的乱序时间是5s
            private Long currentMaxTimestamp = 0L;

            @Nullable
            @Override
            public Watermark getCurrentWatermark() {
                return new Watermark(currentMaxTimestamp - maxOutOfOrderness);
            }

            @Override
            public long extractTimestamp(StudentInfo studentInfo, long l) {
                currentMaxTimestamp = Math.max(studentInfo.getTimestamp(), currentMaxTimestamp);
                System.out.println("currentMaxTimestamp:"+currentMaxTimestamp);
                return studentInfo.getTimestamp();
            }
        });

        return dataStream;
    }

    //重要:timestamp作为proctimeAttribute返回类型,必须设置为SQL_TIMESTAMP类型
    @Override
    public TableSchema getTableSchema() {
        String[] names = new String[] {"name" , "sex" , "course" , "score" , "timestamp"};
        TypeInformation<StudentInfo>[] types = new TypeInformation[] {Types.STRING(), Types.STRING(), Types.STRING(), Types.FLOAT(), Types.SQL_TIMESTAMP()};
        TableSchema tableSchema = new TableSchema(names,types);
        return  tableSchema;
    }

    @Override
    public List<RowtimeAttributeDescriptor> getRowtimeAttributeDescriptors() {
        RowtimeAttributeDescriptor rowtimeAttrDescr = new RowtimeAttributeDescriptor(
                "timestamp",
                new ExistingField("timestamp"),
                new AscendingTimestamps());
        List<RowtimeAttributeDescriptor> listRowtimeAttrDescr = Collections.singletonList(rowtimeAttrDescr);
        return listRowtimeAttrDescr;
    }

    @Override
    public TypeInformation<StudentInfo> getReturnType() {
        return TypeExtractor.createTypeInfo(StudentInfo.class);
    }
}
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.Tumble;
import org.apache.flink.table.api.java.StreamTableEnvironment;

public class TableStreamFlinkStudentTableSourceTimerTest {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        StreamTableEnvironment streamTableEnvironment = StreamTableEnvironment.create(env);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        // register table source
        streamTableEnvironment.registerTableSource("StudentActions", new StudentActionSource());
        Table windowedTable = streamTableEnvironment
                        .scan("StudentActions")
                        .window((Tumble.over("2.minutes"))
                        .on("timestamp")
                        .as("studentActionWindow"))
                        .groupBy("studentActionWindow,name")
                        .select("name,sum(score) as sum_total_score");

        DataStream<Tuple2<Boolean, StudentScoreResult>> studentScoreResultDataStream = streamTableEnvironment.toRetractStream(windowedTable,StudentScoreResult.class);
        studentScoreResultDataStream.print();

        env.execute("studentScoreAnalyse");
    }
}

上面实例在运行过程中,print一直没有结果信息,数据信息没有统计出来,参考文档书写正确,还要看到的小伙伴指点,具体错误原因在哪里

<think>好的,我现在需要帮用户解决“app-active 也有可能多条数据,去重”的问题。首先,用户之前提到过initial_users太多需要限制500,现在又遇到重复数据的问题,可能他们在处理数据时遇到了重复记录的情况,比如用户活跃数据被多次记录。 首先,我需要确定用户的具体场景。app-active可能是指应用程序的活跃用户数据,可能存在同一条数据被多次记录的情况,比如用户在同一天多次打开应用,导致重复记录。这时候需要去重,确保每个用户或每条数据只保留一条有效记录。 接下来,用户可能的真实需求是什么?他们可能需要确保数据的唯一性,以便进行准确的分析或统计。比如,计算每日活跃用户数(DAU)时,重复数据会导致结果偏高,影响准确性。因此,去重是关键步骤。 然后,我要考虑不同的去重方法。常见的有数据库层面的去重,比如使用DISTINCT或GROUP BY,或者在应用层处理,比如用Python的集合或Pandas的drop_duplicates。此外,可能还需要考虑实时处理和批处理的区别,比如使用消息队列或流处理框架来处理实时数据,避免重复写入。 另外,用户可能还关心如何避免重复数据产生。比如在前端提交时做校验,或者在数据库设置唯一索引,防止重复插入。需要根据具体情况选择合适的方法,比如如果是日志数据,可能无法完全避免重复,但可以在处理时去重。 还需要注意去重的依据是什么。用户可能需要根据某个或某几个字段来判断是否重复,比如用户ID和时间戳的组合。这时候需要明确去重的键,确保正确性。例如,同一用户在同一时间段内的多次活跃记录可能需要保留最新的一条,或者合并多条记录的信息。 此外,用户可能对性能有要求,尤其是当数据量很大时。比如使用数据库的DISTINCT可能效率不高,可以考虑在查询时优化,或者使用临时表来存储去重后的数据。在应用层处理时,需要注意内存的使用,避免因为数据量过大导致内存溢出。 最后,可能需要给出一些具体的代码示例,比如SQL查询、Python的Pandas操作,或者是使用Redis的集合进行实时去重。同时提醒用户注意事务管理,确保去重操作不会影响数据的一致性,以及记录日志以便追踪问题。</think>针对 "app-active 可能存在多条重复数据需要去重" 的场景,以下是技术方案和实现思路: --- ### **问题分析** 当应用活跃数据(app-active)因以下原因产生重复时需去重: - **埋点重复上报**(网络重试、客户端异常) - **分布式系统幂等失效**(多个节点重复处理) - **时间窗口重叠**(如用户快速切换页面产生多次记录) - **业务逻辑缺陷**(如未校验设备唯一性) --- ### **去重方案** #### 1. **数据库层去重** **适用场景**:离线数据分析或批量处理 ```sql -- 方式1:DISTINCT 去重(全字段严格匹配) SELECT DISTINCT user_id, app_id, active_time FROM app_active_logs; -- 方式2:窗口函数保留最新记录(按时间保留唯一值) WITH ranked AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY device_id, DATE(active_time) ORDER BY active_time DESC ) AS rn FROM app_active_logs ) SELECT * FROM ranked WHERE rn = 1; ``` #### 2. **应用层去重** **适用场景**:实时数据处理或内存可控的小数据集 ```python # 使用唯一键集合过滤 dedup_cache = set() cleaned_data = [] for record in raw_data: # 以 用户ID+日期小时 作为去重键(例:user123_20231015_14) unique_key = f"{record['user_id']}_{record['active_time'][:13]}" if unique_key not in dedup_cache: dedup_cache.add(unique_key) cleaned_data.append(record) ``` #### 3. **消息队列去重** **适用场景**:高并发实时数据流(如Kafka) ```java // 使用 Kafka 生产者端幂等配置 properties.put("enable.idempotence", "true"); properties.put("acks", "all"); ``` #### 4. **Redis 布隆过滤器** **适用场景**:海量数据去重(允许极小概率误判) ```python import redis from redisbloom.client import Client rb = Client(host='localhost', port=6379) rb.bfCreate('active_dedup', 0.01, 1000000) # 预期存储100万条,误判率1% def deduplicate(user_id, timestamp): key = f"{user_id}_{timestamp//3600}" # 按小时分片 if rb.bfExists('active_dedup', key): return False rb.bfAdd('active_dedup', key) return True ``` --- ### **进阶策略** #### 1. **复合去重规则** | 字段组合 | 适用场景 | |-------------------------|-----------------------------| | 设备ID + 事件时间戳 | 硬件设备日志去重 | | 用户ID + 行为类型 + 日期 | 用户行为分析(如每日首次点击)| | IP + 用户代理 + 路径 | 防止恶意刷量 | #### 2. **Lambda架构混合去重** ```mermaid graph LR 实时流-->|Kafka+Redis|实时去重看板 批处理-->|Hive/Spark|离线修正补偿 ``` #### 3. **动态时间窗口** ```python # 根据业务波动自动调整去重时间窗口 def get_dedup_window(event_type): return { 'login': 24*3600, # 登录行为24小时去重 'page_view': 300, # 页面浏览5分钟去重 'payment': 0 # 支付行为不允许去重 }[event_type] ``` --- ### **注意事项** 1. **数据完整性**:支付类关键数据需谨慎去重 2. **存储成本**:布隆过滤器需预估容量避免扩容 3. **时区处理**:跨时区系统需统一UTC时间判断 4. **冷热分离**:历史数据归档后关闭去重逻辑 5. **监控指标**:需跟踪重复率指标(如 `dup_count/total_records`) 可根据具体技术栈(如 Flink/Spark Streaming)选择适合的方案组合。若需更高可靠性,可结合数据库唯一索引(如 `ALTER TABLE app_active ADD UNIQUE (dedup_key)`)实现双重保障。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

springk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值