【问题标题】:Akka streams: Simulating a failed stream with OverflowStrategy.fail()Akka 流:使用 OverflowStrategy.fail() 模拟失败的流
【发布时间】:2020-04-16 21:43:12
【问题描述】:

我是 Akka 和 Akka 流的新手。我创建了一个虚拟流,我希望它以异常结束,因为我的 map() 函数非常慢,我将缓冲区设置为 1

所以我的问题分为两部分:

  1. 为什么这段代码可以正常工作?
  2. 如何模拟溢出? (用于学习目的)
    import akka.NotUsed;
    import akka.actor.ActorSystem;
    import akka.stream.OverflowStrategy;
    import akka.stream.javadsl.Sink;
    import akka.stream.javadsl.Source;

    public class Application {

        public static void main(String[] args) {
            final ActorSystem system = ActorSystem.create("reactive-test");
            Source<Integer, NotUsed> source =
                    Source.range(0, 10000000)
                    .buffer(1, OverflowStrategy.fail())
                    .map(Application::doubleInt);      
            source.runWith(Sink.foreach(a -> System.out.println(a)), system);
        }

        private static Integer doubleInt(int i) {
            try {
                Thread.sleep(2_000);
            } catch (Exception e) {
                System.out.println(e);
            }
            return 2 * i;
        }
    }

【问题讨论】:

    标签: java akka akka-stream


    【解决方案1】:

    为什么这段代码可以正常工作?

    原因是背压。 Source 不会产生比您的 sink 消耗更多的元素,因此慢速 sink 会直接影响元素的生成速度。因此,您的缓冲区永远不会溢出。

    如何模拟溢出? (用于学习目的)

    有一个渴望消耗但同时又很慢的水槽。可以通过添加grouped(1000) 来模拟它,该grouped(1000) 创建1000 个元素的列表并将其传递到下游。

    import akka.NotUsed;
    import akka.actor.ActorSystem;
    import akka.stream.OverflowStrategy;
    import akka.stream.javadsl.Sink;
    import akka.stream.javadsl.Source;
    
    public class StreamsBufJava {
    
        public static void main(String[] args) {
            final ActorSystem system = ActorSystem.create("reactive-test");
            Source<Integer, NotUsed> source =
                    Source.range(0, 10000000)
                            .buffer(1, OverflowStrategy.fail())
                            .grouped(1000)
                            .mapConcat(list -> list)
                            .map(StreamsBufJava::doubleInt);
    
    
            source.runWith(Sink.foreach(System.out::println), system);
        }
    
        private static Integer doubleInt(int i) {
            try {
                Thread.sleep(2_000);
            } catch (Exception e) {
                System.out.println(e);
            }
    
            return 2 * i;
        }
    }
    
    

    生产

    0
    2
    [ERROR] [04/17/2020 09:40:47.671] [reactive-test-akka.actor.default-dispatcher-5] [Buffer(akka://reactive-test)] Failing because buffer is full and overflowStrategy is: [Fail] in stream [class akka.stream.impl.fusing.Buffer$$anon$26]
    4
    6
    8
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      相关资源
      最近更新 更多