Flink初试——对接Kafka

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
实时计算 Flink 版,5000CU*H 3个月
简介: Flink初试——对接Kafka

本篇文章我们用 Flink Kafka Connector对接Kafka,实现一个简单的报警业务。我们暂时不去谈论理论,先上手实现这个简单的需求。

flink-connector-kafka是 flink 内置的Kafka连接器,包含了从topic读取数据的Flink Kafka Consumer 和 向topic写入数据的flink kafka producer,除了基本功能外还提供了基于 checkpoint 机制提供了完美的容错能力。

本文基于flink 1.10.1 和 flink-connector-kafka-0.10_2.11版本,pom如下:

<dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-kafka-0.10_2.11</artifactId>
            <version>1.10.0</versio>
</dependency>

以企业常见的预警业务为例,本文要实现的业务逻辑很简单,当设备上报的油桶余量不足10%时,便生成一个报警,这里我们将报警写入MySQL,以供web业务端展示报警报表。

首先我们用网络数据调试器向网关模拟发送数据,网关会将数据解析后写入kafka


kafka-console-consumer --bootstrap-server cdh1.macro.com:9092,cdh2.macro.com:9092,cdh3.macro.com:9092 --from-beginning --topic fill
{"addTime":1593147840000,"currentAmount":0.3,"devId":"XT365-000170","devStatus":"1","ifOffline":"1","ip":"127.0.0.1","leftTankAmount":5,"realTotalAmount":2377.39,"registerTime":1606658457000,"settingAmount":0.3,"tankCapacity":1000,"totalAmount":2017.9315}
{"addTime":1593147840000,"currentAmount":0.3,"devId":"XT365-000170","devStatus":"1","ifOffline":"1","ip":"127.0.0.1","leftTankAmount":5,"realTotalAmount":2377.69,"registerTime":1606658458000,"settingAmount":0.3,"tankCapacity":1000,"totalAmount":2017.9315}
^C20/11/29 23:26:55 INFO internals.ConsumerCoordinator: [Consumer clientId=consumer-console-consumer-82199-1, groupId=console-consumer-82199] Revoke previously assigned partitions fill-0
20/11/29 23:26:55 INFO internals.AbstractCoordinator: [Consumer clientId=consumer-console-consumer-82199-1, groupId=console-consumer-82199] Member consumer-console-consumer-82199-1-aa5fc2e6-1f06-4714-9d89-fe080a9400e2 sending LeaveGroup request to coordinator cdh2.macro.com:9092 (id: 2147483598 rack: null) due to the consumer is being closed
Processed a total of 1200 messages


可以看到我们已经向kafka生产了1200条数据了

接下来我们写一段代码来消费kafka数据,并将报警结果写入MySQL

import com.alibaba.fastjson.JSONObject;
import com.iiot.bean.InSufficient;
import com.iiot.commCommon.Fill;
import com.iiot.jdbc.MySQLSinks;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
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.windowing.windows.TimeWindow;
import org.apache.flink.streaming.api.windowing.time.Time;
import java.util.List;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010;
import org.apache.flink.util.Collector;
import org.apache.flink.shaded.guava18.com.google.common.collect.Lists;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import java.util.Properties;
public class InSufficientOilAlarms {
    public static void main(String[] args) throws Exception{
        //构建流执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //kafka
        Properties prop = new Properties();
        prop.put("bootstrap.servers", "cdh1.macro.com:9092,cdh2.macro.com:9092,cdh3.macro.com:9092");
//        prop.put("zookeeper.connect", "localhost:2181");
        prop.put("group.id", "fill6");
        prop.put("key.serializer", "org.apache.kafka.common.serialization.StringDeserializer");
        prop.put("value.serializer", "org.apache.kafka.common.serialization.StringDeserializer");
        prop.put("auto.offset.reset", "earliest");
        DataStreamSource<String> stream = env
                .addSource(new FlinkKafkaConsumer010<String>(
                        "fill",
                        new SimpleStringSchema(), prop)).
                //单线程打印,控制台不乱序,不影响结果
                setParallelism(1);
        //从kafka里读取数据,转换成Person对象
        DataStream<Fill> dataStream = stream.map(value ->
                JSONObject.parseObject(value, Fill.class)
        );
        SingleOutputStreamOperator<InSufficient> result = dataStream.map(new MapFunction<Fill, InSufficient>() {
                           @Override
                           public InSufficient map(Fill fill) throws Exception {
                               InSufficient inSufficient = new InSufficient();
                               Float leftTankAmount = fill.getLeftTankAmount();
                               Float tankCapacity = fill.getTankCapacity();
                               String devCode = fill.getDevId();
                               long timeBegin = fill.getAddTime().getTime();
                               System.out.println("devCode:-------------------------------------------------" + devCode);
                               String alarmType = "";
                               if ((leftTankAmount / tankCapacity) < 0.1 ) {
                                   alarmType = "inSufficientOil";
                                   inSufficient.setDev_code(devCode);
                                   inSufficient.setCreateTime(System.currentTimeMillis());
                                   inSufficient.setTimeBegin(timeBegin);
                                   inSufficient.setAlarmType(alarmType);
                                   inSufficient.setRemainAmount(leftTankAmount);
                               }
                               return inSufficient;
                           }
                       }
        );
        //收集5秒钟的总数
        result.timeWindowAll(Time.seconds(5L)).
                apply(new AllWindowFunction<InSufficient, List<InSufficient>, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow timeWindow, Iterable<InSufficient> iterable, Collector<List<InSufficient>> out) throws Exception {
                        List<InSufficient> inSufficients = Lists.newArrayList(iterable);
                        if(inSufficients.size() > 0) {
                            System.out.println("5秒的总共收到的条数:" + inSufficients.size());
                            out.collect(inSufficients);
                        }
                    }
                })
                //sink 到数据库
                .addSink(new MySQLSinks());
        //打印到控制台
        //.print();
        env.execute("kafka 消费任务开始");
    }
}


将项目打包,传到集群中,用Flink on YARN的方式运行作业

[root@cdh3 bin]# flink run -m yarn-cluster -c com.iiot.alarm.InSufficientOilAlarms /data0/flinkdemo/stream-1.0-SNAPSHOT-jar-with-dependencies.jar 
20/11/30 01:40:15 INFO cli.CliFrontend: --------------------------------------------------------------------------------
20/11/30 01:40:15 INFO cli.CliFrontend:  Starting Command Line Client (Version: 1.10.0-csa1.2.0.0, Rev:04dddd1, Date:29.05.2020 @ 14:54:45 UTC)
20/11/30 01:40:15 INFO cli.CliFrontend:  OS current user: root
20/11/30 01:40:16 INFO cli.CliFrontend:  Current Hadoop/Kerberos user: hdfs
20/11/30 01:40:16 INFO cli.CliFrontend:  JVM: Java HotSpot(TM) 64-Bit Server VM - Oracle Corporation - 1.8/25.171-b11
20/11/30 01:40:16 INFO cli.CliFrontend:  Maximum heap size: 3531 MiBytes
20/11/30 01:40:16 INFO cli.CliFrontend:  JAVA_HOME: /usr/java/latest
20/11/30 01:40:16 INFO cli.CliFrontend:  Hadoop version: 2.7.5
20/11/30 01:40:16 INFO cli.CliFrontend:  JVM Options:
20/11/30 01:40:16 INFO cli.CliFrontend:     -Datlas.conf=/etc/atlas/conf/
20/11/30 01:40:16 INFO cli.CliFrontend:     -Dlog.file=/var/log/flink/flink-root-client-cdh3.macro.com.log
20/11/30 01:40:16 INFO cli.CliFrontend:     -Dlog4j.configuration=file:/etc/flink/conf/log4j-cli.properties
20/11/30 01:40:16 INFO cli.CliFrontend:     -Dlogback.configurationFile=file:/etc/flink/conf/logback.xml
20/11/30 01:40:16 INFO cli.CliFrontend:  Program Arguments:
20/11/30 01:40:16 INFO cli.CliFrontend:     run
20/11/30 01:40:16 INFO cli.CliFrontend:     -m
20/11/30 01:40:16 INFO cli.CliFrontend:     yarn-cluster
20/11/30 01:40:16 INFO cli.CliFrontend:     -c
20/11/30 01:40:16 INFO cli.CliFrontend:     com.iiot.alarm.InSufficientOilAlarms
20/11/30 01:40:16 INFO cli.CliFrontend:     /data0/flinkdemo/stream-1.0-SNAPSHOT-jar-with-dependencies.jar
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Client environment:java.io.tmpdir=/tmp
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Client environment:java.compiler=<NA>
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Client environment:os.name=Linux
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Client environment:os.arch=amd64
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Client environment:os.version=3.10.0-327.el7.x86_64
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Client environment:user.name=root
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Client environment:user.home=/root
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Client environment:user.dir=/opt/cloudera/parcels/FLINK-1.10.0-csa1.2.0.0-cdh7.1.1.0-565-3454809/bin
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Client environment:os.memory.free=134MB
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Client environment:os.memory.max=3531MB
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Client environment:os.memory.total=359MB
20/11/30 01:40:51 INFO utils.Compatibility: Using emulated InjectSessionExpiration
20/11/30 01:40:51 INFO imps.CuratorFrameworkImpl: Starting
20/11/30 01:40:51 INFO zookeeper.ZooKeeper: Initiating client connection, connectString=cdh1.macro.com:2181,cdh2.macro.com:2181,cdh3.macro.com:2181 sessionTimeout=60000 watcher=org.apache.flink.shaded.curator.org.apache.curator.ConnectionState@1460c81d
20/11/30 01:40:51 INFO common.X509Util: Setting -D jdk.tls.rejectClientInitiatedRenegotiation=true to disable client-initiated TLS renegotiation
20/11/30 01:40:51 INFO zookeeper.ClientCnxnSocket: jute.maxbuffer value is 4194304 Bytes
20/11/30 01:40:51 INFO zookeeper.ClientCnxn: zookeeper.request.timeout value is 0. feature enabled=
20/11/30 01:40:51 WARN zookeeper.ClientCnxn: SASL configuration failed: javax.security.auth.login.LoginException: No JAAS configuration section named 'Client' was found in specified JAAS configuration file: '/tmp/jaas-8202592158525653501.conf'. Will continue connection to Zookeeper server without SASL authentication, if Zookeeper server allows it.
20/11/30 01:40:51 INFO zookeeper.ClientCnxn: Opening socket connection to server cdh1.macro.com/192.168.0.171:2181
20/11/30 01:40:51 INFO zookeeper.ClientCnxn: Socket connection established, initiating session, client: /192.168.0.208:38183, server: cdh1.macro.com/192.168.0.171:2181
20/11/30 01:40:51 ERROR curator.ConnectionState: Authentication failed
20/11/30 01:40:51 INFO imps.CuratorFrameworkImpl: Default schema
20/11/30 01:40:51 INFO zookeeper.ClientCnxn: Session establishment complete on server cdh1.macro.com/192.168.0.171:2181, sessionid = 0x3008be9995512b4, negotiated timeout = 60000
20/11/30 01:40:51 INFO state.ConnectionStateManager: State change: CONNECTED
20/11/30 01:40:51 INFO imps.EnsembleTracker: New config event received: {server.1=cdh2.macro.com:3181:4181:participant, version=0, server.3=cdh1.macro.com:3181:4181:participant, server.2=cdh3.macro.com:3181:4181:participant}
20/11/30 01:40:51 ERROR imps.EnsembleTracker: Invalid config event received: {server.1=cdh2.macro.com:3181:4181:participant, version=0, server.3=cdh1.macro.com:3181:4181:participant, server.2=cdh3.macro.com:3181:4181:participant}
20/11/30 01:40:51 INFO imps.EnsembleTracker: New config event received: {server.1=cdh2.macro.com:3181:4181:participant, version=0, server.3=cdh1.macro.com:3181:4181:participant, server.2=cdh3.macro.com:3181:4181:participant}
20/11/30 01:40:51 ERROR imps.EnsembleTracker: Invalid config event received: {server.1=cdh2.macro.com:3181:4181:participant, version=0, server.3=cdh1.macro.com:3181:4181:participant, server.2=cdh3.macro.com:3181:4181:participant}
20/11/30 01:40:52 INFO leaderretrieval.ZooKeeperLeaderRetrievalService: Starting ZooKeeperLeaderRetrievalService /leader/rest_server_lock.

可以在YARN作业中看到Flink的做作业一直在运行。

flink dashboard也可以看到作业一直在运行:

进入YARN reourcemanager里面查看作业运行日志:

可以看到MySQL已经插入数据了。


相关文章
|
2月前
|
消息中间件 关系型数据库 MySQL
大数据-117 - Flink DataStream Sink 案例:写出到MySQL、写出到Kafka
大数据-117 - Flink DataStream Sink 案例:写出到MySQL、写出到Kafka
184 0
|
2月前
|
消息中间件 NoSQL Kafka
Flink-10 Flink Java 3分钟上手 Docker容器化部署 JobManager TaskManager Kafka Redis Dockerfile docker-compose
Flink-10 Flink Java 3分钟上手 Docker容器化部署 JobManager TaskManager Kafka Redis Dockerfile docker-compose
67 4
|
2月前
|
消息中间件 NoSQL Kafka
大数据-116 - Flink DataStream Sink 原理、概念、常见Sink类型 配置与使用 附带案例1:消费Kafka写到Redis
大数据-116 - Flink DataStream Sink 原理、概念、常见Sink类型 配置与使用 附带案例1:消费Kafka写到Redis
192 0
|
2月前
|
消息中间件 资源调度 大数据
大数据-112 Flink DataStreamAPI 程序输入源 DataSource 基于文件、集合、Kafka连接器
大数据-112 Flink DataStreamAPI 程序输入源 DataSource 基于文件、集合、Kafka连接器
47 0
|
消息中间件 Kafka 流计算
|
3月前
|
运维 数据处理 数据安全/隐私保护
阿里云实时计算Flink版测评报告
该测评报告详细介绍了阿里云实时计算Flink版在用户行为分析与标签画像中的应用实践,展示了其毫秒级的数据处理能力和高效的开发流程。报告还全面评测了该服务在稳定性、性能、开发运维及安全性方面的卓越表现,并对比自建Flink集群的优势。最后,报告评估了其成本效益,强调了其灵活扩展性和高投资回报率,适合各类实时数据处理需求。
|
1月前
|
存储 分布式计算 流计算
实时计算 Flash – 兼容 Flink 的新一代向量化流计算引擎
本文介绍了阿里云开源大数据团队在实时计算领域的最新成果——向量化流计算引擎Flash。文章主要内容包括:Apache Flink 成为业界流计算标准、Flash 核心技术解读、性能测试数据以及在阿里巴巴集团的落地效果。Flash 是一款完全兼容 Apache Flink 的新一代流计算引擎,通过向量化技术和 C++ 实现,大幅提升了性能和成本效益。
1161 73
实时计算 Flash – 兼容 Flink 的新一代向量化流计算引擎
zdl
|
1月前
|
消息中间件 运维 大数据
大数据实时计算产品的对比测评:实时计算Flink版 VS 自建Flink集群
本文介绍了实时计算Flink版与自建Flink集群的对比,涵盖部署成本、性能表现、易用性和企业级能力等方面。实时计算Flink版作为全托管服务,显著降低了运维成本,提供了强大的集成能力和弹性扩展,特别适合中小型团队和业务波动大的场景。文中还提出了改进建议,并探讨了与其他产品的联动可能性。总结指出,实时计算Flink版在简化运维、降低成本和提升易用性方面表现出色,是大数据实时计算的优选方案。
zdl
155 56
|
5月前
|
存储 监控 大数据
阿里云实时计算Flink在多行业的应用和实践
本文整理自 Flink Forward Asia 2023 中闭门会的分享。主要分享实时计算在各行业的应用实践,对回归实时计算的重点场景进行介绍以及企业如何使用实时计算技术,并且提供一些在技术架构上的参考建议。
862 7
阿里云实时计算Flink在多行业的应用和实践
|
4月前
|
SQL 消息中间件 Kafka
实时计算 Flink版产品使用问题之如何在EMR-Flink的Flink SOL中针对source表单独设置并行度
实时计算Flink版作为一种强大的流处理和批处理统一的计算框架,广泛应用于各种需要实时数据处理和分析的场景。实时计算Flink版通常结合SQL接口、DataStream API、以及与上下游数据源和存储系统的丰富连接器,提供了一套全面的解决方案,以应对各种实时计算需求。其低延迟、高吞吐、容错性强的特点,使其成为众多企业和组织实时数据处理首选的技术平台。以下是实时计算Flink版的一些典型使用合集。
下一篇
DataWorks