假设我们有一个数据源,其中包含每个地铁站每分钟的进站人数,数据格式如下:
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可以通过以下步骤实现:
- 引入Kafka相关的依赖,例如
flink-connector-kafka
和kafka-clients
。 - 创建一个
Properties
对象,用于存储Kafka相关的配置信息,例如Kafka服务器地址、消费者组ID等。 - 使用
FlinkKafkaConsumer
创建一个Kafka数据源,指定要消费的Kafka主题和上述Properties
对象。 - 替换原始的数据源为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分区的数量、设置消费者组的数量、调整数据的序列化方式等。