Akka Test Example under Spring

Source: Internet
Author: User

1. Test Objective: verify that Akka ensures that each instance of the actor runs in its own lightweight thread and has its own queue, guaranteeing FIFO processing of each message.

2, Akka actor is both a transmitter and receiver, send messages and receive messages must pass their own OnReceive method.

3. If you use the same instance test obtained from spring, the result is that each actor instance is self-contained, and the order of sending and receiving is consistent.

Annotationconfigapplicationcontext CTX =          new Annotationconfigapplicationcontext ();        Ctx.scan ("Com.anyvape.common.akka");        Ctx.refresh ();        Get hold of the actor system        Actorsystem system = Ctx.getbean (Actorsystem.class);        Use the Spring Extension to create props for a named actor bean        actorref greeter = system.actorof (        Countingprov Ider.get (System). Props ("Countingactor"), "counter");                Actorref greetprinter = system.actorof (        countingprovider.get (System). Props ("Greetprinter"), "Greetprinter");        for (int i=0;i<100;i++) {            Greeter.tell (new greeting (string.valueof (i)), greetprinter);        }



4. Multiple actor instances of the same actor class send a message test to the same actor instance. A breakpoint is added to the receiver at the time of the test, and when the sender finishes sending, the breakpoint is opened and the receiving party prints in the same order as the sending order.

Annotationconfigapplicationcontext CTX =          new Annotationconfigapplicationcontext ();        Ctx.scan ("Com.anyvape.common.akka");        Ctx.refresh ();        Get hold of the actor system        Actorsystem system = Ctx.getbean (Actorsystem.class);        Use the Spring Extension to create props for a named actor bean        actorref greeter = system.actorof (        Countingprov Ider.get (System). Props ("Countingactor"), "counter");                Actorref greetprinter = system.actorof (        countingprovider.get (System). Props ("Greetprinter"), "Greetprinter");        for (int i=0;i<100;i++) {    greeter = system.actorof (        countingprovider.get (System). Props ("Countingactor" ), "Counter". Concat (String.valueof (i)));        Greeter.tell (New greeting (string.valueof (i)), greetprinter);        



5. Code

Spring's annotation configuration class

Import Akka.actor.actorsystem;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.applicationcontext;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.configuration;import Static com.anyvape.common.akka.producer.countingactorfactory.countingprovider;/** * The application configuration. */@Configurationclass Appconfiguration {  //The application context is needed to initialize the Akka Spring extension< c1/> @Autowired  private ApplicationContext applicationcontext;  /**   * Actor System singleton for this application.   *  /@Bean public  Actorsystem Actorsystem () {    Actorsystem system = actorsystem.create ("akkajavaspring");    Initialize the application context in the Akka Spring Extension    countingprovider.get (System). Initialize ( ApplicationContext);    return system;  }}



Get the actor's proxy class from the Spring management context

Import Akka.actor.actor;import Akka.actor.indirectactorproducer;import org.springframework.context.applicationcontext;/** * A proxy class that obtains an object from the spring context, the instance must implement an interface method that produces the actor and defines an interface method for the Production class type * an Actor producer that lets Spring create the actor instances. */public class Actorproducer implements Indirectactorproducer {  final applicationcontext applicationcontext;  Final String Actorbeanname;  Public Actorproducer (ApplicationContext applicationcontext,                             String actorbeanname) {    This.applicationcontext = ApplicationContext;    This.actorbeanname = Actorbeanname;  }  @Override public  Actor Produce () {    return (Actor) Applicationcontext.getbean (actorbeanname);  }  @Override public  class<? extends Actor> Actorclass () {    return (class<? extends actor>) Applicationcontext.gettype (Actorbeanname);  }}



Factory class, using the agent above to generate the actor

Import Akka.actor.abstractextensionid;import Akka.actor.extendedactorsystem;import Akka.actor.extension;import Akka.actor.props;import org.springframework.context.applicationcontext;/** * Call Actorproducer Create actor * an Akka Extension to provide access to Spring managed Actor Beans. */public class Countingactorfactory extends abstractextensionid<countingactorfactory.springext> {/** * the Iden   Tifier used to access the springextension.  */public static countingactorfactory Countingprovider = new Countingactorfactory ();   /** * is used by Akka to instantiate the Extension identified by this * Extensionid and internal use only.  */@Override public springext createextension (Extendedactorsystem system) {return new Springext ();   }/** * the Extension implementation.    */public static class Springext implements Extension {private volatile applicationcontext applicationcontext;     /** * Used to initialize the Spring application context for the extension. * @paRam ApplicationContext */public void Initialize (ApplicationContext applicationcontext) {This.applicationcont    ext = ApplicationContext;     }/** * Create a Props for the specified actorbeanname using the * Springactorproducer class. * * @param actorbeanname The name of the actor bean to create Props for * @return A Props that would create the NA Med actor Bean Using Spring */public Props Props (String actorbeanname) {return props.create (actorproducer.cl    ApplicationContext, Actorbeanname); }  }}



Role 1

Import Java.util.random;import akka.actor.untypedactor;import Javax.inject.inject;import Javax.inject.Named;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.annotation.Scope; Import Org.springframework.stereotype.component;import com.anyvape.common.akka.service.countingservice;/** * Asynchronously counts how often a user uses this keyword * * @note the scope here is prototype since we want to create a new actor * instance for use of this BEA N. */@Component ("Countingactor") public class Countingactor extends Untypedactor {public static class Count {} public St  Atic class Get {} @Autowired countingservice countingservice;  private int count = 0; @Override public void OnReceive (Object message) throws Exception {if (message instanceof Count) {count = Counti      Ngservice.increment (count);      System.out.println ("--------" +count);    Thread.Sleep (New Random (). Nextint (400) + 1);    } else if (message instanceof Get) {Getsender (). Tell (Count, Getself ()); } else{unhandled (message); }  }}



Role 2

Import Java.util.random;import Com.anyvape.common.akka.hello2.greeting;import Akka.actor.untypedactor;public class Greetprinter extends Untypedactor {public    void OnReceive (Object message) {        if (message instanceof greeting)            System.out.println ("-------------Re:" + ((greeting) message). message);        try {thread.sleep (New Random (). Nextint (5*1000) + 1),} catch (Interruptedexception e) {//TODO auto-generated catch Blocke. Printstacktrace ();}        Getsender (). Tell (New Com.anyvape.common.akka.Hello2.End (((greeting) message), getself ());}    }



Akka Test Example under Spring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.