Flink通过滚动窗口达到滑动窗口目的 节省内存和CPU资源(背压)

2023-11-02 08:59

本文主要是介绍Flink通过滚动窗口达到滑动窗口目的 节省内存和CPU资源(背压),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Flink在实时处理滑动窗口数据时, 由于窗口时间长, 滑动较为频繁, 导致算子计算压力过大, 下游算子计算速度抵不上上游数据产生速度, 会出现背压现象.

需求: 统计6小时用户设备共同用户数, 每10min统计一次

公共类

@Data
@AllArgsConstructor
// flatMap转换对象
private static class UserDevice {private final String userId;private final String deviceId;
}@Data
// 用户设备统计结果
// 第一个map存放用户最新设备, 直接put覆盖, 取最新设备
// 第二个map存放设备对应用户, 因为要去重, 所以使用set存放
private static class UserDeviceSummary {private final Map<String, String> userDevices = new HashMap<>(60000); // (uid, did)private final Map<String, Set<String>> deviceUsers = new HashMap<>(60000); // (did, Set<uid>)
}

原算子 滑动窗口

dataStreamSource.flatMap((FlatMapFunction<JSONArray, UserDevice>) (array, collector) -> {try {array.forEach(e -> {JSONObject one = (JSONObject) e;// 只处理opay_show事件  app_name in ('opay', '1')if (one.containsKey("uid") && one.containsKey("did")) {collector.collect(new UserDevice(one.getString("uid"), one.getString("did")));}});} catch (Exception ignored) {}}).returns(TypeInformation.of(new TypeHint<UserDevice>() {})).name("Stream flat map").timeWindowAll(Time.hours(6), Time.minutes(10)) // 滑动窗口.allowedLateness(Time.minutes(1)).process(new ProcessAllWindowFunction<UserDevice, UserDeviceSummary, TimeWindow>() {@Overridepublic void process(ProcessAllWindowFunction<UserDevice, UserDeviceSummary, TimeWindow>.Context context, Iterable<UserDevice> elements, Collector<UserDeviceSummary> out) throws Exception {UserDeviceSummary uds = new UserDeviceSummary();for (UserDevice ud : elements) {try {// 不用线程安全集合, 提升效率 由于并行度为1, 应该不会有并发uds.getUserDevices().put(ud.getUserId(), ud.getDeviceId());if (!uds.getDeviceUsers().containsKey(ud.getDeviceId())) {uds.getDeviceUsers().put(ud.getDeviceId(), new HashSet<>());}uds.getDeviceUsers().get(ud.getDeviceId()).add(ud.getUserId());} catch (Exception ignore) {}}out.collect(uds);}}).name("Process to Map").process(new ProcessFunction<UserDeviceSummary, Map<String, Integer>>() {@Overridepublic void processElement(UserDeviceSummary uds, ProcessFunction<UserDeviceSummary, Map<String, Integer>>.Context ctx, Collector<Map<String, Integer>> out) throws Exception {Map<String, Integer> result = new HashMap<>();for (String uid : uds.getUserDevices().keySet()) {try {int count = uds.getDeviceUsers().get(uds.getUserDevices().get(uid)).size();result.put(uid, count);} catch (Exception e) {System.out.println("Process for sink error: " + e.getMessage());}}out.collect(result);// 清空数据 协助gcuds.getUserDevices().clear();uds.getDeviceUsers().clear();result.clear();}}).name("User device calc").print();

开始运行正常, 随着时间的推移, 数据堆积越来越大, 滑动过程中, 最大会有6h / 10min = 36次并行计算, cpu压力比较大, 并行度只能为1
在这里插入图片描述

优化

使用滚动窗口替换滑动窗口, 既节省了内存, 也减少了cpu计算. 每10min滚动一次, 外部使用queue存储, 最大保存36个元素


private static final int SUMMARY_LIST_CAPACITY = 36;
// merge list中36个元素 生成一个新的元素, 输出到下游
private static UserDeviceSummary merge(List<UserDeviceSummary> list) {UserDeviceSummary result = list.get(0);// 此处最好应该添加summary时间, 避免长时间没数据流入导致数据错误int length = Math.min(list.size(), SUMMARY_LIST_CAPACITY);System.out.println("Merge tumbling summary: " + length);for (int i = 1; i < length; i++) {UserDeviceSummary current = list.get(i);result.getUserDevices().putAll(current.getUserDevices());current.getDeviceUsers().forEach((key, value) -> result.getDeviceUsers().merge(key, value, (s1, s2) -> {s1.addAll(s2);return s1;}));}return result;
}
List<UserDeviceSummary> list = new LinkedList<>();dataStreamSource.flatMap((FlatMapFunction<JSONArray, UserDevice>) (array, collector) -> {try {array.forEach(e -> {JSONObject one = (JSONObject) e;// 只处理opay_show事件  app_name in ('opay', '1')if (one.containsKey("uid") && one.containsKey("did")) {collector.collect(new UserDevice(one.getString("uid"), one.getString("did")));}});} catch (Exception ignored) {}}).returns(TypeInformation.of(new TypeHint<UserDevice>() {})).name("Stream flat map").timeWindowAll(Time.minutes(10)) // 使用滚动窗口代替滑动窗口, 节省资源.process(new ProcessAllWindowFunction<UserDevice, UserDeviceSummary, TimeWindow>() {@Overridepublic void process(ProcessAllWindowFunction<UserDevice, UserDeviceSummary, TimeWindow>.Context context, Iterable<UserDevice> elements, Collector<UserDeviceSummary> out) throws Exception {UserDeviceSummary uds = new UserDeviceSummary();for (UserDevice ud : elements) {try {// 不用线程安全集合, 提升效率uds.getUserDevices().put(ud.getUserId(), ud.getDeviceId());if (!uds.getDeviceUsers().containsKey(ud.getDeviceId())) {uds.getDeviceUsers().put(ud.getDeviceId(), new HashSet<>());}uds.getDeviceUsers().get(ud.getDeviceId()).add(ud.getUserId());} catch (Exception ignore) {}}list.add(uds);if (list.size() > SUMMARY_LIST_CAPACITY) {list.remove(0);}out.collect(merge(list));}}).name("Process to Map").process(new ProcessFunction<UserDeviceSummary, Map<String, Integer>>() {@Overridepublic void processElement(UserDeviceSummary uds, ProcessFunction<UserDeviceSummary, Map<String, Integer>>.Context ctx, Collector<Map<String, Integer>> out) throws Exception {Map<String, Integer> result = new HashMap<>();for (String uid : uds.getUserDevices().keySet()) {try {int count = uds.getDeviceUsers().get(uds.getUserDevices().get(uid)).size();result.put(uid, count);} catch (Exception e) {System.out.println("Process for sink error: " + e.getMessage());}}out.collect(result);uds.getUserDevices().clear();uds.getDeviceUsers().clear();result.clear();}}).name("User device calc").print();

再次部署, 服务运行正常!

这篇关于Flink通过滚动窗口达到滑动窗口目的 节省内存和CPU资源(背压)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/329526

相关文章

C++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

Windows的CMD窗口如何查看并杀死nginx进程

《Windows的CMD窗口如何查看并杀死nginx进程》:本文主要介绍Windows的CMD窗口如何查看并杀死nginx进程问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录Windows的CMD窗口查看并杀死nginx进程开启nginx查看nginx进程停止nginx服务

Redis过期删除机制与内存淘汰策略的解析指南

《Redis过期删除机制与内存淘汰策略的解析指南》在使用Redis构建缓存系统时,很多开发者只设置了EXPIRE但却忽略了背后Redis的过期删除机制与内存淘汰策略,下面小编就来和大家详细介绍一下... 目录1、简述2、Redis http://www.chinasem.cn的过期删除策略(Key Expir

html 滚动条滚动过快会留下边框线的解决方案

《html滚动条滚动过快会留下边框线的解决方案》:本文主要介绍了html滚动条滚动过快会留下边框线的解决方案,解决方法很简单,详细内容请阅读本文,希望能对你有所帮助... 滚动条滚动过快时,会留下边框线但其实大部分时候是这样的,没有多出边框线的滚动条滚动过快时留下边框线的问题通常与滚动条样式和滚动行

SpringBoot整合Apache Flink的详细指南

《SpringBoot整合ApacheFlink的详细指南》这篇文章主要为大家详细介绍了SpringBoot整合ApacheFlink的详细过程,涵盖环境准备,依赖配置,代码实现及运行步骤,感兴趣的... 目录1. 背景与目标2. 环境准备2.1 开发工具2.2 技术版本3. 创建 Spring Boot

Spring Boot 整合 Apache Flink 的详细过程

《SpringBoot整合ApacheFlink的详细过程》ApacheFlink是一个高性能的分布式流处理框架,而SpringBoot提供了快速构建企业级应用的能力,下面给大家介绍Spri... 目录Spring Boot 整合 Apache Flink 教程一、背景与目标二、环境准备三、创建项目 & 添

Java进程CPU使用率过高排查步骤详细讲解

《Java进程CPU使用率过高排查步骤详细讲解》:本文主要介绍Java进程CPU使用率过高排查的相关资料,针对Java进程CPU使用率高的问题,我们可以遵循以下步骤进行排查和优化,文中通过代码介绍... 目录前言一、初步定位问题1.1 确认进程状态1.2 确定Java进程ID1.3 快速生成线程堆栈二、分析

conda安装GPU版pytorch默认却是cpu版本

《conda安装GPU版pytorch默认却是cpu版本》本文主要介绍了遇到Conda安装PyTorchGPU版本却默认安装CPU的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的... 目录一、问题描述二、网上解决方案罗列【此节为反面方案罗列!!!】三、发现的根本原因[独家]3.1 p

Linux CPU飙升排查五步法解读

《LinuxCPU飙升排查五步法解读》:本文主要介绍LinuxCPU飙升排查五步法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录排查思路-五步法1. top命令定位应用进程pid2.php top-Hp[pid]定位应用进程对应的线程tid3. printf"%