Frage

I have some pseudo code that I was hoping some with experience could tell me if akka would be used like this, and if not, how I could re-work my design to fit into akka's best practice.

class Article(val words: Word) {

  val tokens: List[Word]

}

class Word(..) {


  def parseWords() {
    val word = .....
    tokenActor ! word    // this is suppose to add the word to the tokens List

  }

}

So the pattern is basically I will create a Article which will have a word object. Then the word object will start doing some parsing, and at times it needs to pass data back to the Article object to "share memory by communicating" like in Go's coroutines.

I know Scala had an inbox type system but not going forward we are suppose to use Akka, but I find that Akka has poor documention when it comes to examples etc.

Can someone tell me if the above design is possible? And could I use this inside of a play application?

War es hilfreich?

Lösung

A sample for you. Here Tokenizer takes seq of items to parse and gives them out to Parser to do the parsing. Parser than reports back results to the Tokenizer.

import akka.actor._
import com.typesafe.config.ConfigFactory

case object Go
case object Done
case object GoAway

class Tokenizer(items: Seq[String]) extends Actor {
  val kid = context.actorOf(Props[Parser])
  var tokens: List[String] = List.empty
  override def receive: akka.actor.Actor.Receive = {
    case Go => // start process
      items.foreach(kid ! _)
      kid ! GoAway
    case Done => // report results
      println(tokens.mkString(":"))
      self ! PoisonPill // shut down
    case s: String => // data from kid
      tokens = s :: tokens
  }
}

class Parser extends Actor {
  override def receive: Receive = {
    case GoAway =>
      sender ! Done
      self ! PoisonPill // or context.stop(self)
    case s: String =>
      s.split("\\.").foreach(sender ! _)
  }
}

object G extends App {

  val config = ConfigFactory.parseString("" +
    "akka.loglevel=DEBUG\n" +
    "akka.debug.lifecycle=on\n" +
    "akka.debug.receive=on\n" +
    "akka.debug.event-stream=on\n" +
    "akka.debug.unhandled=on\n" +
    ""
  )

  val system = ActorSystem("mine", config)
  val doer = system.actorOf(Props(new Tokenizer(Seq("191.168.1.1", "192.168.1.2"))))

  doer ! Go

  system.shutdown()
  system.awaitTermination()

}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top