parent
f73f01f616
commit
3b2da5e3aa
@ -0,0 +1,19 @@
|
||||
package day3
|
||||
import akka.actor.Actor;
|
||||
import akka.actor.ActorSystem;
|
||||
import akka.actor.Props
|
||||
|
||||
class HelloActor extends Actor {
|
||||
def receive: Actor.Receive = {
|
||||
case "hello" => println("Hi")
|
||||
case _ => println("Wut")
|
||||
}
|
||||
}
|
||||
|
||||
object ActOne extends App {
|
||||
val system = ActorSystem("ActOne")
|
||||
val act = system.actorOf(Props[HelloActor], name = "alice")
|
||||
act ! "hello"
|
||||
act ! "one"
|
||||
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
package day3
|
||||
import akka.actor.Actor;
|
||||
import akka.pattern.ask;
|
||||
import akka.actor.ActorSystem;
|
||||
import akka.actor.Props
|
||||
import akka.util.Timeout;
|
||||
import scala.io.Source
|
||||
import scala.concurrent.duration._;
|
||||
import scala.concurrent.{Await, ExecutionContext, Future}
|
||||
|
||||
|
||||
case class Get(url : String)
|
||||
|
||||
object Fetch {
|
||||
def getPageSize(url: String) = Source.fromURL(url).mkString.length()
|
||||
}
|
||||
|
||||
class PageLoader extends Actor {
|
||||
|
||||
def receive: Actor.Receive = {
|
||||
case Get(url) => sender ! Fetch.getPageSize(url)
|
||||
}
|
||||
}
|
||||
|
||||
object LoadPages extends App {
|
||||
val system = ActorSystem("ActOne")
|
||||
val urls = List(
|
||||
"http://www.amazon.com",
|
||||
"http://jxs.me",
|
||||
"http://www.example.com",
|
||||
"http://sdf.org"
|
||||
)
|
||||
|
||||
|
||||
def timeMethod(method: () => Unit) = {
|
||||
val start = System.nanoTime
|
||||
method()
|
||||
val end = System.nanoTime
|
||||
println("Method took " + (end - start) / 1000000000.0 + " seconds.")
|
||||
}
|
||||
|
||||
def getPageSizeSequentially() = {
|
||||
for (url <- urls) {
|
||||
println("Size for " + url + ": " + Fetch.getPageSize(url))
|
||||
}
|
||||
}
|
||||
|
||||
def getPageSizeConcurrently() = {
|
||||
implicit val timeout = Timeout(5.seconds)
|
||||
val futures = urls.map(url => {
|
||||
val act = system.actorOf(Props[PageLoader], name = url.replace("/", ""))
|
||||
act ? Get(url)
|
||||
})
|
||||
for (future <- futures) {
|
||||
val result = Await.result(future, timeout.duration)
|
||||
println(result)
|
||||
}
|
||||
}
|
||||
|
||||
timeMethod { getPageSizeSequentially }
|
||||
timeMethod { getPageSizeConcurrently }
|
||||
|
||||
}
|
Loading…
Reference in new issue