![](/img/trans.png)
[英]How to send elements to a Source.actorRef or a Source.queue in Java
[英]Understanding backpressure in akka streams Source.queue
我正在嘗試akka流,但我不能讓背壓在我的簡單例子中工作。 我很幸運沒有經歷過akka(溪流),所以可能我錯過了一些大事。
我正在生產(提供隊列)整數比消耗它們更快,所以我認為背壓會起作用。我的目標是始終使用放入隊列中的最新項目(這就是為什么我有bufferSize = 1和OverflowStrategy .dropHead()在源隊列上)。
public class SimpleStream {
public static void main(String[] argv) throws InterruptedException {
final ActorSystem system = ActorSystem.create("akka-streams");
final Materializer materializer = ActorMaterializer.create(system);
final Procedure<Integer> slowConsumer = (i) -> {
System.out.println("consuming [" + i + "]");
ThreadUtils.sleepQuietly(1000, TimeUnit.MILLISECONDS);
};
final SourceQueue<Integer> q = Sink
.<Integer>foreach(slowConsumer)
.runWith(Source.<Integer>queue(1, OverflowStrategy.dropHead()), materializer);
final AtomicInteger i = new AtomicInteger(0);
final Thread t = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
int n = i.incrementAndGet();
q.offer(n);
System.out.println("produced: [" + n + "]");
ThreadUtils.sleepQuietly(500, TimeUnit.MILLISECONDS);
}
});
t.setName("ticking");
t.start();
// run some time... to observe the effects.
ThreadUtils.sleepQuietly(1, TimeUnit.HOURS);
t.interrupt();
t.join();
// eventually shutdown akka here...
}
}
然而,這是結果:
produced: [1]
consuming [1]
produced: [2]
produced: [3]
consuming [2] <-- Expected to be consuming 3 here.
produced: [4]
produced: [5]
consuming [3] <-- Expected to be consuming 5 here.
produced: [6]
produced: [7]
請忽略這里的線程內容,只是假冒從外部源獲取數據(如果我必須在實際項目中使用它,就會發生這種情況)。
知道我錯過了什么嗎?
Source.queue
終止Source.queue
的信號。 這就是Source.queue方法接受OverflowStrategy
。 如果可以在隊列的上游發信號通知背壓,那么就不需要處理隊列可能溢出的情況。 但由於背壓不會傳播通過隊列,因此需要定義策略來處理比消費者更快的生產者。
通過典型的流,最終的Source
接收來自Sink
需求以產生更多結果。 但是,使用從Source.queue
創建的流,“最終源”是隊列。 如果有的話,這個隊列只能排出內容。 它不能向上游發出信號以產生更多結果,因為上游位於offer
方法的另一側。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.