Akka
Akka
Anil Dhulipalla
what is Akka?
Akka is an open-source toolkit and runtime to build concurrent, distributed, fault tolerant applications.
Akka provides the following features
Installation
Akka Actor
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_2.10</artifactId>
<version>2.3-M1</version>
</dependency>
Actor Model
Actors instead of Objects
No shared state between actors
Asynchronous message passing
Actors
Define Actor
public class CheckOutChildActor extends UntypedActor {
private static final Logger LOG = Logger.getLogger(CheckOutChildActor.class);
public CheckOutChildActor() throws DatabaseException, ConfigurationException{
this.checkoutBasicService = new CheckoutBasicService();
}
@Override
public void preStart() {
LOG.info("Starting CheckOutChildActor instance hashcode # {} -" + this.hashCode());
}
@Override
public void onReceive(Object o) throws Exception {
try {
if (o instanceof Checkout) {
Checkout checkout = (Checkout) o;
CheckoutDTO checkoutDTO = checkoutBasicService.getCheckout(checkout);
getSender().tell(checkoutDTO, getSelf());
} else {
unhandled(o);
}
} catch (IncompleteCheckoutException e) {
getSender().tell(new Status.Success(e), getSelf());
throw e;
} catch (DatabaseException e) {
getSender().tell(new Status.Failure(e), getSelf());
throw e;
} catch (CustomException e) {
getSender().tell(new Status.Failure(e), getSelf());
throw e;
}catch (Exception e) {
LOG.error("CHILD ERROR",e);
getSender().tell(new Status.Failure(e), getSelf());
throw e;
}
}
@Override
public void postStop() {
LOG.info("Stopping CheckOutChildActor instance hashcode # {} -" + this.hashCode());
}
}
Actor system
Remote Actor
Routing
A router routes incoming messages to outbound actors
RoundRobinPool
SmallestMailboxPool
RandomPool
ScatterGatherFirstCompletedPool
BroadcastPool
Unit Testing
public class CheckOutChildActorTest extends TestKit {
private static ActorSystem actorSystem = ActorSystem.create("childActorTestKit");
private TestActorRef<CheckOutChildActor> childActorRef;
@Mock
private CheckoutBasicService checkoutBasicService;
@InjectMocks
private CheckOutChildActor checkOutChildActor;
public CheckOutChildActorTest() {
super(actorSystem);
}
@Before
public void setUp() throws Exception {
System.setProperty("user.home", System.getProperty("user.dir") + "/src/test/resources");
childActorRef = TestActorRef.apply(Props.create(CheckOutChildActor.class),
actorSystem);
checkOutChildActor = childActorRef.underlyingActor();
MockitoAnnotations.initMocks(this);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testChildActor() throws Exception {
Checkout checkout = CheckoutGenerator.generateCheckout(2L);
CheckoutDTO checkoutDTO = CheckoutGenerator.generateCheckoutDTO(2L, 2L);
Thank You