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;
    }
}

}

相关推荐
招财小梗10 分钟前
沈阳AI企业服务真能降本增效?
大数据·人工智能·python
github_czy26 分钟前
tf-idf讲解
大数据·人工智能·microsoft
whcyhhh36 分钟前
头歌实践教学平台:数据科学与大数据技术导论(九下)
大数据·python
字节跳动数据平台1 小时前
iDA:从 ChatBI 到专业数据分析助手的演进之路
大数据
故七月1 小时前
基于FAQ结构化开发的区域GEO排名提升技术方案——以四川成都服务商万域智瞰场景为例
大数据·人工智能
金立基包装胶水1 小时前
格拉辛纸热封后容易开胶怎么办?
大数据·笔记·其他
这就是佬们吗1 小时前
AI Agent 的四根支柱:LLM、工具、记忆与规划是如何协同的
大数据·数据库·人工智能
林澈在路上1 小时前
AI做歌用哪个最好 2026国产AI音乐工具评测
大数据·人工智能·aigc·音视频·音频
加速财经2 小时前
从 WEEX 看全球数字资产服务平台的发展趋势观察
大数据·人工智能
金立基包装胶水2 小时前
牛皮纸袋用什么热封胶最好?
大数据·笔记·其他