使用flink写一个计算地铁日流量的代码demo

假设我们有一个数据源,其中包含每个地铁站每分钟的进站人数,数据格式如下:

station_id,timestamp,num_people

其中,station_id表示地铁站编号,timestamp表示时间戳,num_people表示每分钟进站人数。我们的目标是计算每个地铁站每天的总进站人数

import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SubwayDailyFlow {
    public static void main(String[] args) throws Exception {
        // 1. 创建 Flink 流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 2. 读取数据源
        DataStream<String> source = env.socketTextStream("localhost", 8888);

        // 3. 数据转换,将每条记录转换为 (station_id, num_people) 的形式
        DataStream<Tuple2<String, Integer>> data = source.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String record) throws Exception {
                String[] fields = record.split(",");
                String stationId = fields[0];
                int numPeople = Integer.parseInt(fields[2]);
                return new Tuple2<>(stationId, numPeople);
            }
        });

        // 4. 按照地铁站编号进行分组
        DataStream<Tuple2<String, Integer>> groupedData = data.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> record) throws Exception {
                return record.f0;
            }
        });

        // 5. 计算每个地铁站每天的总进站人数
        DataStream<Tuple3<String, String, Integer>> dailyData = groupedData.timeWindow(Time.days(1))
                .aggregate(new AggregateFunction<Tuple2<String, Integer>, Tuple2<Integer, Integer>, Tuple2<Integer, Integer>>() {
                    @Override
                    public Tuple2<Integer, Integer> createAccumulator() {
                        return new Tuple2<>(0, 0);
                    }

                    @Override
                    public Tuple2<Integer, Integer> add(Tuple2<String, Integer> value, Tuple2<Integer, Integer> accumulator) {
                        accumulator.f0 += value.f1;
                        accumulator.f1 += 1;
                        return accumulator;
                    }

                    @Override
                    public Tuple2<Integer, Integer> getResult(Tuple2<Integer, Integer> accumulator) {
                        return accumulator;
                    }

                    @Override
                    public Tuple2<Integer, Integer> merge(Tuple2<Integer, Integer> a, Tuple2<Integer, Integer> b) {
                        a.f0 += b.f0;
                        a.f1 += b.f1;
                        return a;
                    }
                })
                .map(new MapFunction<Tuple2<Integer, Integer>, Tuple3<String, String, Integer>>() {
                    @Override
                    public Tuple3<String, String, Integer> map(Tuple2<Integer, Integer> value) throws Exception {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String date = dateFormat.format(new Date());
                        return new Tuple3<>(value.f0, date, value.f1);
                    }
                });

        // 6. 输出结果
        dailyData.print();

        // 7. 执行任务
        env.execute("SubwayDailyFlow");
    }
}

在上述代码中,我们使用socketTextStream读取数据源,然后使用map函数将每条记录转换为(station_id, num_people)的形式。接着,使用keyBy函数按照地铁站编号进行分组,然后使用timeWindow函数按照每天的时间窗口进行聚合操作。在聚合操作中,我们使用AggregateFunction计算每个地铁站每天的总进站人数和进站次数,然后使用map函数将结果转换为(station_id, date, total_num_people)的形式。最后,使用print函数输出结果,然后使用execute函数执行任务。

需要注意的是,在实际应用中,还需要对数据的特点和业务需求进行深入分析和优化,以使得整个作业的执行效率最大化。例如,可以使用reduce函数或自定义ReduceFunction来减少聚合操作的计算量,或使用keyBy函数对地铁站编号进行哈希分区等

将数据源从socketTextStream改为Kafka可以通过以下步骤实现:

  1. 引入Kafka相关的依赖,例如flink-connector-kafkakafka-clients
  2. 创建一个Properties对象,用于存储Kafka相关的配置信息,例如Kafka服务器地址、消费者组ID等。
  3. 使用FlinkKafkaConsumer创建一个Kafka数据源,指定要消费的Kafka主题和上述Properties对象。
  4. 替换原始的数据源为Kafka数据源,即将socketTextStream改为addSource函数,并将其参数改为上述Kafka数据源。

下面是一个将数据源改为Kafka的示例代码:

import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.util.serialization.SimpleStringSchema;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class SubwayDailyFlow {
    public static void main(String[] args) throws Exception {
        // 1. 创建 Flink 流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 2. 创建 Kafka 数据源
        Properties properties = new Properties();
        properties.setProperty("bootstrap.servers", "localhost:9092");
        properties.setProperty("group.id", "subway-consumer-group");
        FlinkKafkaConsumer<String> kafkaConsumer = new FlinkKafkaConsumer<>("subway-topic", new SimpleStringSchema(), properties);

        // 3. 读取数据源
        DataStream<String> source = env.addSource(kafkaConsumer);

        // 4. 数据转换,将每条记录转换为 (station_id, num_people) 的形式
        DataStream<Tuple2<String, Integer>> data = source.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String record) throws Exception {
                String[] fields = record.split(",");
                String stationId = fields[0];
                int numPeople = Integer.parseInt(fields[2]);
                return new Tuple2<>(stationId, numPeople);
            }
        });

        // 5. 按照地铁站编号进行分组
        DataStream<Tuple2<String, Integer>> groupedData = data.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> record) throws Exception {
                return record.f0;
            }
        });

        // 6. 计算每个地铁站每天的总进站人数
        DataStream<Tuple3<String, String, Integer>> dailyData = groupedData.timeWindow(Time.days(1))
                .aggregate(new AggregateFunction<Tuple2<String, Integer>, Tuple2<Integer, Integer>, Tuple2<Integer, Integer>>() {
                    @Override
                    public Tuple2<Integer, Integer> createAccumulator() {
                        return new Tuple2<>(0, 0);
                    }

                    @Override
                    public Tuple2<Integer, Integer> add(Tuple2<String, Integer> value, Tuple2<Integer, Integer> accumulator) {
                        accumulator.f0 += value.f1;
                        accumulator.f1 += 1;
                        return accumulator;
                    }

                    @Override
                    public Tuple2<Integer, Integer> getResult(Tuple2<Integer, Integer> accumulator) {
                        return accumulator;
                    }

                    @Override
                    public Tuple2<Integer, Integer> merge(Tuple2<Integer, Integer> a, Tuple2<Integer, Integer> b) {
                        a.f0 += b.f0;
                        a.f1 += b.f1;
                        return a;
                    }
                })
                .map(new MapFunction<Tuple2<Integer, Integer>, Tuple3<String, String, Integer>>() {
                    @Override
                    public Tuple3<String, String, Integer> map(Tuple2<Integer, Integer> value) throws Exception {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String date = dateFormat.format(new Date());
                        return new Tuple3<>(value.f0, date, value.f1);
                    }
                });

        // 7. 输出结果
        dailyData.print();

        // 8. 执行任务
        env.execute("SubwayDailyFlow");
    }
}

在上述代码中,我们使用Properties对象存储Kafka相关的配置信息,然后使用FlinkKafkaConsumer创建一个Kafka数据源,指定要消费的Kafka主题和上述Properties对象。接着,使用addSource函数将Kafka数据源作为数据源,替换原始的socketTextStream函数。需要注意的是,Kafka数据源消费的数据格式可能与原始数据源不同,因此可能需要修改map函数中的转换逻辑。

需要注意的是,在实际应用中,还需要对Kafka数据源的特点和业务需求进行深入分析和优化,以使得整个作业的执行效率最大化。例如,可以调整Kafka分区的数量、设置消费者组的数量、调整数据的序列化方式等。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值