核心特点

  1. 单线程执行:非并行源始终以并行度1运行,即使设置更高并行度也无效
  2. 资源独占:占用一个完整的Task Slot
  3. 顺序处理:保证数据处理的顺序性

典型应用场景

  • 单点数据源(单个文件、单个数据库连接)
  • 状态集中管理(全局计数器)
  • 外部系统限制(仅支持单连接的系统)
  • 需要严格顺序保证的场景

代码示例

public class NoParallelSource implements SourceFunction<String> {
    private Long count = 1L;
    private boolean running = true;

    @Override
    public void run(SourceContext<String> ctx) throws Exception {
        while (running) {
            count++;
            ctx.collect(String.valueOf(count));
            Thread.sleep(1000);
        }
    }

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

使用方式:

DataStream<String> stream = env.addSource(new NoParallelSource()).setParallelism(1);

优缺点

  • 优势: 实现简单、避免并发冲突、状态管理清晰
  • 劣势: 吞吐量有限,容易成为性能瓶颈