flink:自定义数据分区

shuffle随机地将数据分配到下游的子任务。

rebalance用round robbin模式将数据分配到下游的子任务。

global把所有的数据都分配到一个分区。

partitionCustom: 自定义数据分区。

package cn.edu.tju.demo;

import org.apache.flink.api.common.functions.;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.collector.selector.OutputSelector;
import org.apache.flink.streaming.api.datastream.
;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import org.apache.flink.streaming.api.functions.co.CoMapFunction;

import org.apache.flink.streaming.api.functions.source.SourceFunction;

import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

import org.apache.flink.util.Collector;

import org.apache.kafka.clients.consumer.ConsumerConfig;

import org.apache.kafka.clients.producer.ProducerConfig;

import org.apache.kafka.common.serialization.StringDeserializer;

import org.apache.kafka.common.serialization.StringSerializer;

import java.util.*;

public class Test12 {

public static void main(String\[\] args) throws Exception {

StreamExecutionEnvironment environment = StreamExecutionEnvironment

.getExecutionEnvironment();

复制代码
    DataStreamSource<String> mySource = environment.addSource(new MySourceFunction());
    SingleOutputStreamOperator<Tuple2<String, Integer>> mapStream = mySource.map(new MapFunction<String, Tuple2<String, Integer>>() {
        @Override
        public Tuple2<String, Integer> map(String value) throws Exception {
            return new Tuple2<>(value, new Random().nextInt(10));
        }
    });

    DataStream<Tuple2<String, Integer>> resultStream = mapStream.partitionCustom(new MyPartitioner(), 1);


    resultStream.print();

    environment.execute("my job");

}

public static class MyPartitioner implements Partitioner<Integer>{

    @Override
    public int partition(Integer key, int partitions) {
        return key % partitions;
    }
}



public static class MySourceFunction implements SourceFunction<String> {
    private boolean runningFlag = true;
    @Override
    public void run(SourceContext<String> ctx) throws Exception {
        while (runningFlag){
            ctx.collect("hi world");
            ctx.collect("hello world");
            Thread.sleep(30000);
        }
    }

    @Override
    public void cancel() {
        runningFlag = false;
    }
}

}

相关推荐
liuliuqiqirr1 小时前
2026最新两款AI编程工具深度对比实测
大数据·ai编程
cspttty1 小时前
数字经济没有项目经验,怎么补就业短板
大数据·人工智能
数智化管理手记1 小时前
应收应付资金占用过高怎么办?应收应付搭配账龄分析怎么做
大数据·网络·数据库·人工智能·数据挖掘
大大大大晴天1 小时前
Hudi技术内幕:Compaction原理与实践
大数据
zyplayer-doc2 小时前
研发接口文档怎么长期维护:zyplayer-doc把API、Markdown和变更记录放进同一个知识库
大数据·数据库·人工智能·笔记·pdf·ocr
奥莱维2 小时前
经济型酒店智能客控轻量化方案
大数据·网络·人工智能
新芒3 小时前
【无标题】
大数据·人工智能
BOTTLE_平3 小时前
工具篇:用什么AI与选型避坑指南
大数据·人工智能
阿标在干嘛4 小时前
从HTTP到WebSocket:招投标信息实时推送系统的协议选型与架构设计
大数据·微服务·架构
苏州IT威翰德13 小时前
算力资产“续命”专家:苏州威翰德科技赋能NVIDIA高端AI芯片芯片级维修
大数据·人工智能