2018-03-13 23:45:55 +09:00
|
|
|
/*
|
2019-01-02 18:55:26 +08:00
|
|
|
* Copyright (C) 2018-2019 Lightbend Inc. <https://www.lightbend.com>
|
2018-03-13 23:45:55 +09:00
|
|
|
*/
|
|
|
|
|
|
2017-03-16 09:30:00 +01:00
|
|
|
package jdocs.cluster;
|
2017-02-14 13:10:23 +02:00
|
|
|
|
|
|
|
|
import java.util.ArrayList;
|
|
|
|
|
import java.util.List;
|
2018-05-14 10:22:02 +02:00
|
|
|
import java.time.Duration;
|
2017-02-14 13:10:23 +02:00
|
|
|
|
2017-03-16 09:30:00 +01:00
|
|
|
import jdocs.cluster.StatsMessages.JobFailed;
|
|
|
|
|
import jdocs.cluster.StatsMessages.StatsResult;
|
2017-02-14 13:10:23 +02:00
|
|
|
import akka.actor.ActorRef;
|
|
|
|
|
import akka.actor.ReceiveTimeout;
|
2017-02-23 00:50:07 +05:00
|
|
|
import akka.actor.AbstractActor;
|
2017-02-14 13:10:23 +02:00
|
|
|
|
|
|
|
|
//#aggregator
|
2017-02-23 00:50:07 +05:00
|
|
|
public class StatsAggregator extends AbstractActor {
|
2017-02-14 13:10:23 +02:00
|
|
|
|
|
|
|
|
final int expectedResults;
|
|
|
|
|
final ActorRef replyTo;
|
|
|
|
|
final List<Integer> results = new ArrayList<Integer>();
|
|
|
|
|
|
|
|
|
|
public StatsAggregator(int expectedResults, ActorRef replyTo) {
|
|
|
|
|
this.expectedResults = expectedResults;
|
|
|
|
|
this.replyTo = replyTo;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Override
|
|
|
|
|
public void preStart() {
|
2018-05-14 10:22:02 +02:00
|
|
|
getContext().setReceiveTimeout(Duration.ofSeconds(3));
|
2017-02-14 13:10:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Override
|
2017-02-23 00:50:07 +05:00
|
|
|
public Receive createReceive() {
|
|
|
|
|
return receiveBuilder()
|
|
|
|
|
.match(Integer.class, wordCount -> {
|
|
|
|
|
results.add(wordCount);
|
|
|
|
|
if (results.size() == expectedResults) {
|
|
|
|
|
int sum = 0;
|
|
|
|
|
for (int c : results) {
|
|
|
|
|
sum += c;
|
|
|
|
|
}
|
|
|
|
|
double meanWordLength = ((double) sum) / results.size();
|
2017-03-16 09:30:00 +01:00
|
|
|
replyTo.tell(new StatsResult(meanWordLength), getSelf());
|
|
|
|
|
getContext().stop(getSelf());
|
2017-02-23 00:50:07 +05:00
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
.match(ReceiveTimeout.class, x -> {
|
|
|
|
|
replyTo.tell(new JobFailed("Service unavailable, try again later"),
|
2017-03-16 09:30:00 +01:00
|
|
|
getSelf());
|
|
|
|
|
getContext().stop(getSelf());
|
2017-02-23 00:50:07 +05:00
|
|
|
})
|
|
|
|
|
.build();
|
2017-02-14 13:10:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
//#aggregator
|