当前位置: 首页 > news >正文

用Flink对keyed state 状态的代码进行设置TTL(过期时间)和hdfs的checkpoints恢复和配置Flink-conf.yaml

依赖
<dependency><groupId>org.apache.flink</groupId><artifactId>flink-core</artifactId><version>1.8.1</version></dependency><dependency><groupId>org.apache.flink</groupId><artifactId>flink-clients_2.11</artifactId><version>1.8.1</version></dependency><dependency><groupId>org.apache.flink</groupId><artifactId>flink-scala_2.11</artifactId><version>1.8.1</version></dependency><dependency><groupId>org.apache.flink</groupId><artifactId>flink-streaming-scala_2.11</artifactId><version>1.8.1</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.26</version></dependency><!--添加HDFS支持--><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-hdfs</artifactId><version>2.9.2</version></dependency><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-common</artifactId><version>2.9.2</version></dependency><!--添加Kafka支持--><dependency><groupId>org.apache.flink</groupId><artifactId>flink-connector-kafka_2.11</artifactId><version>1.8.1</version></dependency><dependency><groupId>org.apache.flink</groupId><artifactId>flink-json</artifactId><version>1.8.1</version></dependency><dependency><groupId>org.apache.flink</groupId><artifactId>flink-connector-filesystem_2.11</artifactId><version>1.8.1</version></dependency><!--写到Redis中--><dependency><groupId>org.apache.bahir</groupId><artifactId>flink-connector-redis_2.11</artifactId><version>1.0</version></dependency></dependencies><build><plugins><!--在执行package时候,将scala源码编译进jar--><plugin><groupId>net.alchim31.maven</groupId><artifactId>scala-maven-plugin</artifactId><version>4.0.1</version><executions><execution><id>scala-compile-first</id><phase>process-resources</phase><goals><goal>add-source</goal><goal>compile</goal></goals></execution></executions></plugin></plugins></build>
代码
packagecom.baizhi.demo04importorg.apache.flink.streaming.api.CheckpointingModeimportorg.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanupimportorg.apache.flink.streaming.api.scala.{DataStream,StreamExecutionEnvironment,_}object Flink{defmain(args:Array[String]):Unit={val env=StreamExecutionEnvironment.getExecutionEnvironment//开启checkpointenv.enableCheckpointing(7000,CheckpointingMode.EXACTLY_ONCE)//checkpoint必须在2s内完成,如果完成不了终止env.getCheckpointConfig.setCheckpointTimeout(4000)//距离上一次的checkpoint完成之后需要等5s 之后再开启下一次的checkpointenv.getCheckpointConfig.setMinPauseBetweenCheckpoints(5000)env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)//只开启一个checkpoint线程//在退出应用时候,不删除checkpoint数据env.getCheckpointConfig.enableExternalizedCheckpoints(ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)//必须保证任务可以从checkpoint恢复,恢复不成功任务失败env.getCheckpointConfig.setFailOnCheckpointingErrors(true)val data:DataStream[String]=env.socketTextStream("Flink",9999)data.flatMap(line=>line.split("\\s+")).map((_,1)).keyBy(0).map(newCountMapFunction).print()env.execute()}}
packagecom.baizhi.demo04importorg.apache.flink.api.common.functions.RichMapFunctionimportorg.apache.flink.api.common.state.{StateTtlConfig,ValueState,ValueStateDescriptor}importorg.apache.flink.api.common.time.Timeimportorg.apache.flink.configuration.Configurationimportorg.apache.flink.streaming.api.scala._classCountMapFunctionextendsRichMapFunction[(String,Int),(String,Int)]{var state:ValueState[Int]=_ override defmap(value:(String,Int)):(String,Int)={var history=state.value()if(history==null){history=0}state.update(history+value._2)(value._1,history+value._2)}override defopen(parameters:Configuration):Unit={val dec=newValueStateDescriptor[Int]("count",createTypeInformation[Int])//1.创建TTLConfigval ttlConfig=StateTtlConfig.newBuilder(Time.seconds(80))//这是state存活时间10s.setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)//设置过期时间更新方式.setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)//永远不要返回过期的状态//.cleanupInRocksdbCompactFilter(1000)//处理完1000个状态查询时候,会启用一次CompactFilter.build//2.开启TTLdec.enableTimeToLive(ttlConfig)val context=getRuntimeContext state=context.getState(dec)}}
配置Flink的环境
配置Flink-conf.yaml
#==============================================================================# Fault tolerance and checkpointing#==============================================================================# The backend that will be used to store operator state checkpoints if# checkpointing is enabled.## Supported backends are 'jobmanager', 'filesystem', 'rocksdb', or the# <class-name-of-factory>.#state.backend:rocksdb# Directory for checkpoints filesystem, when using any of the default bundled# state backends.#state.checkpoints.dir:hdfs:///flink-checkpoints# Default target directory for savepoints, optional.#state.savepoints.dir:hdfs:///flink-savepoints# Flag to enable/disable incremental checkpoints for backends that# support incremental checkpoints (like the RocksDB state backend).#state.backend.incremental:truestate.backend.rocksdb.ttl.compaction.filter.enabled:true#==============================================================================# HistoryServer#==============================================================================# The HistoryServer is started and stopped via bin/historyserver.sh (start|stop)# Directory to upload completed jobs to. Add this directory to the list of# monitored directories of the HistoryServer as well (see below).jobmanager.archive.fs.dir:hdfs:///completed-jobs/# The address under which the web-based HistoryServer listens.historyserver.web.address:CentOS# The port under which the web-based HistoryServer listens.historyserver.web.port:8082# Comma separated list of directories to monitor for completed jobs.historyserver.archive.fs.dir:hdfs:///completed-jobs/# Interval in milliseconds for refreshing the monitored directories.historyserver.archive.fs.refresh-interval:10000
将hadoop_classpath配置到环境变量中

export HADOOP_CLASSPATH=hadoop classpath

http://www.jsqmd.com/news/1280937/

相关文章:

  • VK视频下载完整指南:三步实现高清视频永久保存
  • 装备质量特性解析:可靠性、维修性与测试性设计
  • TPIC7710EVM评估模块实战:电子驻车制动ASIC硬件在环开发指南
  • 3步实现Office永久免费激活:Ohook完整功能解锁指南
  • 企业级AI工作流安全合规 checklist:覆盖GDPR/等保2.0/金融信创要求,今日限时开放下载
  • 基于Matlab的驾驶员疲劳检测系统设计与优化
  • 北京市马桶疏通 / 管道疏通|本地市民好评,满分十星平台+ ICP 多重备案 | 2026首选小蚁匠 - 欧米到家
  • 2026郑州外包装盒厂家哪家好,彩箱厂家哪家好?选购指南与避坑攻略 - mobible
  • 088、YOLOv8改进实战:TAL任务对齐学习改进——动态标签分配策略对比与调优
  • Avidemux2深度解析:开源视频编辑器的模块化架构与高级应用
  • TI bq76PL536A BMS评估板实战:从硬件连接到软件配置全解析
  • SmolForge自定义皮肤与动画功能详解:打造个性化开发环境
  • AI编码智能体实战:基于Hermes与DeepSeek-Coder实现项目级自动化编程
  • LRU缓存函数实现
  • 用运筹学与深度学习构建个人发展量化分析模型
  • 物联网安全:SE050安全元件与TM4C129XKCZAD的协同设计
  • 基于Arduino与3D打印的静音电动摇奶机DIY全攻略
  • 物联网设备电池管理:NBM7100A与MKV44F64VLH16解决方案
  • 2026年北京公司注册指南:直营与连锁代办怎么选 - 瑞雪中天
  • CVE-2026-31239实战:Mamba模型RCE漏洞检测脚本、漏洞复现与企业安全加固全流程
  • OLED显示器技术突破与市场爆发分析
  • MySQL数据库入门到实战:从零搭建环境到核心SQL语法详解
  • JAVA计算机毕设之基于 SpringBoot 的电商物流包裹收发追踪管理系统设计 中小型企业物流资源统筹管理系统实现(完整前后端代码+说明文档+LW,调试定制等)
  • 3步将键盘变成专业游戏手柄:vJoy虚拟手柄完全指南
  • PHP异步任务处理:原理、实现与性能优化
  • 告别手动重命名!Flut Renamer:跨平台批量文件重命名工具的完美解决方案
  • 物联网设备电源管理:NBM7100A与TM4C1299KCZAD优化方案
  • 循环水水质分析仪厂家——浊度、pH、电导率、氨氮哪家好? - 康宝莱智慧水务
  • 2026年最新!选英语听说智能软件一定要知道的3个核心标准
  • 物联网设备超低功耗设计:延长电池寿命至4.2年的实战方案