Reformating configuration and examples for PDF (Scala, and leftovers). See #2413
This commit is contained in:
parent
309bb53d98
commit
08ef942242
46 changed files with 330 additions and 191 deletions
|
|
@ -235,7 +235,8 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
|
|||
"creating actor with Props" in {
|
||||
//#creating-props
|
||||
import akka.actor.Props
|
||||
val myActor = system.actorOf(Props[MyActor].withDispatcher("my-dispatcher"), name = "myactor2")
|
||||
val myActor = system.actorOf(Props[MyActor].withDispatcher("my-dispatcher"),
|
||||
name = "myactor2")
|
||||
//#creating-props
|
||||
|
||||
system.stop(myActor)
|
||||
|
|
@ -354,7 +355,8 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
|
|||
Await.result(stopped, 6 seconds)
|
||||
// the actor has been stopped
|
||||
} catch {
|
||||
case e: akka.pattern.AskTimeoutException ⇒ // the actor wasn't stopped within 5 seconds
|
||||
// the actor wasn't stopped within 5 seconds
|
||||
case e: akka.pattern.AskTimeoutException ⇒
|
||||
}
|
||||
//#gracefulStop
|
||||
}
|
||||
|
|
|
|||
|
|
@ -87,7 +87,8 @@ class Worker extends Actor with ActorLogging {
|
|||
case _: CounterService.ServiceUnavailable ⇒ Stop
|
||||
}
|
||||
|
||||
// The sender of the initial Start message will continuously be notified about progress
|
||||
// The sender of the initial Start message will continuously be notified
|
||||
// about progress
|
||||
var progressListener: Option[ActorRef] = None
|
||||
val counterService = context.actorOf(Props[CounterService], name = "counter")
|
||||
val totalCount = 51
|
||||
|
|
@ -133,9 +134,10 @@ class CounterService extends Actor {
|
|||
|
||||
// Restart the storage child when StorageException is thrown.
|
||||
// After 3 restarts within 5 seconds it will be stopped.
|
||||
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 5 seconds) {
|
||||
case _: Storage.StorageException ⇒ Restart
|
||||
}
|
||||
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3,
|
||||
withinTimeRange = 5 seconds) {
|
||||
case _: Storage.StorageException ⇒ Restart
|
||||
}
|
||||
|
||||
val key = self.path.name
|
||||
var storage: Option[ActorRef] = None
|
||||
|
|
@ -194,14 +196,15 @@ class CounterService extends Actor {
|
|||
}
|
||||
|
||||
def forwardOrPlaceInBacklog(msg: Any) {
|
||||
// We need the initial value from storage before we can start delegate to the counter.
|
||||
// Before that we place the messages in a backlog, to be sent to the counter when
|
||||
// it is initialized.
|
||||
// We need the initial value from storage before we can start delegate to
|
||||
// the counter. Before that we place the messages in a backlog, to be sent
|
||||
// to the counter when it is initialized.
|
||||
counter match {
|
||||
case Some(c) ⇒ c forward msg
|
||||
case None ⇒
|
||||
if (backlog.size >= MaxBacklog)
|
||||
throw new ServiceUnavailable("CounterService not available, lack of initial value")
|
||||
throw new ServiceUnavailable(
|
||||
"CounterService not available, lack of initial value")
|
||||
backlog = backlog :+ (sender, msg)
|
||||
}
|
||||
}
|
||||
|
|
@ -281,7 +284,8 @@ object DummyDB {
|
|||
|
||||
@throws(classOf[StorageException])
|
||||
def save(key: String, value: Long): Unit = synchronized {
|
||||
if (11 <= value && value <= 14) throw new StorageException("Simulated store failure " + value)
|
||||
if (11 <= value && value <= 14)
|
||||
throw new StorageException("Simulated store failure " + value)
|
||||
db += (key -> value)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -24,12 +24,13 @@ object FaultHandlingDocSpec {
|
|||
import akka.actor.SupervisorStrategy._
|
||||
import scala.concurrent.util.duration._
|
||||
|
||||
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
|
||||
case _: ArithmeticException ⇒ Resume
|
||||
case _: NullPointerException ⇒ Restart
|
||||
case _: IllegalArgumentException ⇒ Stop
|
||||
case _: Exception ⇒ Escalate
|
||||
}
|
||||
override val supervisorStrategy =
|
||||
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
|
||||
case _: ArithmeticException ⇒ Resume
|
||||
case _: NullPointerException ⇒ Restart
|
||||
case _: IllegalArgumentException ⇒ Stop
|
||||
case _: Exception ⇒ Escalate
|
||||
}
|
||||
//#strategy
|
||||
|
||||
def receive = {
|
||||
|
|
@ -45,12 +46,13 @@ object FaultHandlingDocSpec {
|
|||
import akka.actor.SupervisorStrategy._
|
||||
import scala.concurrent.util.duration._
|
||||
|
||||
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
|
||||
case _: ArithmeticException ⇒ Resume
|
||||
case _: NullPointerException ⇒ Restart
|
||||
case _: IllegalArgumentException ⇒ Stop
|
||||
case _: Exception ⇒ Escalate
|
||||
}
|
||||
override val supervisorStrategy =
|
||||
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
|
||||
case _: ArithmeticException ⇒ Resume
|
||||
case _: NullPointerException ⇒ Restart
|
||||
case _: IllegalArgumentException ⇒ Stop
|
||||
case _: Exception ⇒ Escalate
|
||||
}
|
||||
//#strategy2
|
||||
|
||||
def receive = {
|
||||
|
|
|
|||
|
|
@ -55,7 +55,8 @@ trait Foo {
|
|||
|
||||
trait Bar {
|
||||
import TypedActor.dispatcher //So we have an implicit dispatcher for our Promise
|
||||
def doBar(str: String): Future[String] = Promise.successful(str.toUpperCase).future
|
||||
def doBar(str: String): Future[String] =
|
||||
Promise.successful(str.toUpperCase).future
|
||||
}
|
||||
|
||||
class FooBar extends Foo with Bar
|
||||
|
|
@ -106,7 +107,8 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
|
|||
//#typed-actor-create1
|
||||
//#typed-actor-create2
|
||||
val otherSquarer: Squarer =
|
||||
TypedActor(system).typedActorOf(TypedProps(classOf[Squarer], new SquarerImpl("foo")), "name")
|
||||
TypedActor(system).typedActorOf(TypedProps(classOf[Squarer],
|
||||
new SquarerImpl("foo")), "name")
|
||||
//#typed-actor-create2
|
||||
|
||||
//#typed-actor-calls
|
||||
|
|
@ -157,7 +159,8 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
|
|||
try {
|
||||
//#typed-actor-hierarchy
|
||||
//Inside your Typed Actor
|
||||
val childSquarer: Squarer = TypedActor(TypedActor.context).typedActorOf(TypedProps[SquarerImpl]())
|
||||
val childSquarer: Squarer =
|
||||
TypedActor(TypedActor.context).typedActorOf(TypedProps[SquarerImpl]())
|
||||
//Use "childSquarer" as a Squarer
|
||||
//#typed-actor-hierarchy
|
||||
} catch {
|
||||
|
|
@ -167,7 +170,8 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
|
|||
|
||||
"supercharge" in {
|
||||
//#typed-actor-supercharge-usage
|
||||
val awesomeFooBar: Foo with Bar = TypedActor(system).typedActorOf(TypedProps[FooBar]())
|
||||
val awesomeFooBar: Foo with Bar =
|
||||
TypedActor(system).typedActorOf(TypedProps[FooBar]())
|
||||
|
||||
awesomeFooBar.doFoo(10)
|
||||
val f = awesomeFooBar.doBar("yes")
|
||||
|
|
|
|||
|
|
@ -25,7 +25,8 @@ object CustomRoute {
|
|||
}
|
||||
}
|
||||
|
||||
class CustomRouteBuilder(system: ActorSystem, responder: ActorRef) extends RouteBuilder {
|
||||
class CustomRouteBuilder(system: ActorSystem, responder: ActorRef)
|
||||
extends RouteBuilder {
|
||||
def configure {
|
||||
from("jetty:http://localhost:8877/camel/custom").to(responder)
|
||||
}
|
||||
|
|
@ -48,7 +49,8 @@ object CustomRoute {
|
|||
def receive = {
|
||||
case msg: CamelMessage ⇒ throw new Exception("error: %s" format msg.body)
|
||||
}
|
||||
override def onRouteDefinition = (rd) ⇒ rd.onException(classOf[Exception]).handled(true).transform(Builder.exceptionMessage).end
|
||||
override def onRouteDefinition = (rd) ⇒ rd.onException(classOf[Exception]).
|
||||
handled(true).transform(Builder.exceptionMessage).end
|
||||
|
||||
final override def preRestart(reason: Throwable, message: Option[Any]) {
|
||||
sender ! Failure(reason)
|
||||
|
|
|
|||
|
|
@ -19,8 +19,10 @@ object CustomRouteExample {
|
|||
|
||||
class Transformer(producer: ActorRef) extends Actor {
|
||||
def receive = {
|
||||
// example: transform message body "foo" to "- foo -" and forward result to producer
|
||||
case msg: CamelMessage ⇒ producer.forward(msg.mapBody((body: String) ⇒ "- %s -" format body))
|
||||
// example: transform message body "foo" to "- foo -" and forward result
|
||||
// to producer
|
||||
case msg: CamelMessage ⇒
|
||||
producer.forward(msg.mapBody((body: String) ⇒ "- %s -" format body))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -38,7 +40,8 @@ object CustomRouteExample {
|
|||
})
|
||||
}
|
||||
}
|
||||
// the below lines can be added to a Boot class, so that you can run the example from a MicroKernel
|
||||
// the below lines can be added to a Boot class, so that you can run the
|
||||
// example from a MicroKernel
|
||||
val system = ActorSystem("some-system")
|
||||
val producer = system.actorOf(Props[Producer1])
|
||||
val mediator = system.actorOf(Props(new Transformer(producer)))
|
||||
|
|
|
|||
|
|
@ -21,7 +21,8 @@ object HttpExample {
|
|||
def endpointUri = "jetty://http://akka.io/?bridgeEndpoint=true"
|
||||
|
||||
override def transformOutgoingMessage(msg: Any) = msg match {
|
||||
case msg: CamelMessage ⇒ msg.copy(headers = msg.headers ++ msg.headers(Set(Exchange.HTTP_PATH)))
|
||||
case msg: CamelMessage ⇒ msg.copy(headers = msg.headers ++
|
||||
msg.headers(Set(Exchange.HTTP_PATH)))
|
||||
}
|
||||
|
||||
override def routeResponse(msg: Any) { transformer forward msg }
|
||||
|
|
@ -29,13 +30,17 @@ object HttpExample {
|
|||
|
||||
class HttpTransformer extends Actor {
|
||||
def receive = {
|
||||
case msg: CamelMessage ⇒ sender ! (msg.mapBody { body: Array[Byte] ⇒ new String(body).replaceAll("Akka ", "AKKA ") })
|
||||
case msg: Failure ⇒ sender ! msg
|
||||
case msg: CamelMessage ⇒
|
||||
sender ! (msg.mapBody { body: Array[Byte] ⇒
|
||||
new String(body).replaceAll("Akka ", "AKKA ")
|
||||
})
|
||||
case msg: Failure ⇒ sender ! msg
|
||||
}
|
||||
}
|
||||
|
||||
// Create the actors. this can be done in a Boot class so you can
|
||||
// run the example in the MicroKernel. just add the below three lines to your boot class.
|
||||
// run the example in the MicroKernel. just add the three lines below to
|
||||
// your boot class.
|
||||
val system = ActorSystem("some-system")
|
||||
val httpTransformer = system.actorOf(Props[HttpTransformer])
|
||||
val httpProducer = system.actorOf(Props(new HttpProducer(httpTransformer)))
|
||||
|
|
|
|||
|
|
@ -72,7 +72,8 @@ object Introduction {
|
|||
val system = ActorSystem("some-system")
|
||||
val camel = CamelExtension(system)
|
||||
val camelContext = camel.context
|
||||
// camelContext.addComponent("activemq", ActiveMQComponent.activeMQComponent("vm://localhost?broker.persistent=false"))
|
||||
// camelContext.addComponent("activemq", ActiveMQComponent.activeMQComponent(
|
||||
// "vm://localhost?broker.persistent=false"))
|
||||
//#CamelExtensionAddComponent
|
||||
}
|
||||
{
|
||||
|
|
@ -92,12 +93,14 @@ object Introduction {
|
|||
val camel = CamelExtension(system)
|
||||
val actorRef = system.actorOf(Props[MyEndpoint])
|
||||
// get a future reference to the activation of the endpoint of the Consumer Actor
|
||||
val activationFuture = camel.activationFutureFor(actorRef)(timeout = 10 seconds, executor = system.dispatcher)
|
||||
val activationFuture = camel.activationFutureFor(actorRef)(timeout = 10 seconds,
|
||||
executor = system.dispatcher)
|
||||
//#CamelActivation
|
||||
//#CamelDeactivation
|
||||
system.stop(actorRef)
|
||||
// get a future reference to the deactivation of the endpoint of the Consumer Actor
|
||||
val deactivationFuture = camel.deactivationFutureFor(actorRef)(timeout = 10 seconds, executor = system.dispatcher)
|
||||
val deactivationFuture = camel.deactivationFutureFor(actorRef)(timeout = 10 seconds,
|
||||
executor = system.dispatcher)
|
||||
//#CamelDeactivation
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -45,7 +45,8 @@ object Producers {
|
|||
}
|
||||
val system = ActorSystem("some-system")
|
||||
val receiver = system.actorOf(Props[ResponseReceiver])
|
||||
val forwardResponse = system.actorOf(Props(new Forwarder("http://localhost:8080/news/akka", receiver)))
|
||||
val forwardResponse = system.actorOf(Props(
|
||||
new Forwarder("http://localhost:8080/news/akka", receiver)))
|
||||
// the Forwarder sends out a request to the web page and forwards the response to
|
||||
// the ResponseReceiver
|
||||
forwardResponse ! "some request"
|
||||
|
|
|
|||
|
|
@ -151,7 +151,8 @@ object DispatcherDocSpec {
|
|||
def this(settings: ActorSystem.Settings, config: Config) = this()
|
||||
|
||||
// The create method is called to create the MessageQueue
|
||||
final override def create(owner: Option[ActorRef], system: Option[ActorSystem]): MessageQueue =
|
||||
final override def create(owner: Option[ActorRef],
|
||||
system: Option[ActorSystem]): MessageQueue =
|
||||
new QueueBasedMessageQueue with UnboundedMessageQueueSemantics {
|
||||
final val queue = new ConcurrentLinkedQueue[Envelope]()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,7 +20,9 @@ import akka.testkit.AkkaSpec
|
|||
//#extension
|
||||
class SettingsImpl(config: Config) extends Extension {
|
||||
val DbUri: String = config.getString("myapp.db.uri")
|
||||
val CircuitBreakerTimeout: Duration = Duration(config.getMilliseconds("myapp.circuit-breaker.timeout"), TimeUnit.MILLISECONDS)
|
||||
val CircuitBreakerTimeout: Duration =
|
||||
Duration(config.getMilliseconds("myapp.circuit-breaker.timeout"),
|
||||
TimeUnit.MILLISECONDS)
|
||||
}
|
||||
//#extension
|
||||
|
||||
|
|
@ -29,7 +31,8 @@ object Settings extends ExtensionId[SettingsImpl] with ExtensionIdProvider {
|
|||
|
||||
override def lookup = Settings
|
||||
|
||||
override def createExtension(system: ExtendedActorSystem) = new SettingsImpl(system.settings.config)
|
||||
override def createExtension(system: ExtendedActorSystem) =
|
||||
new SettingsImpl(system.settings.config)
|
||||
}
|
||||
//#extensionid
|
||||
|
||||
|
|
|
|||
|
|
@ -151,7 +151,8 @@ class FutureDocSpec extends AkkaSpec {
|
|||
result must be(4)
|
||||
|
||||
val failedFilter = future1.filter(_ % 2 == 1).recover {
|
||||
case m: NoSuchElementException ⇒ 0 //When filter fails, it will have a java.util.NoSuchElementException
|
||||
// When filter fails, it will have a java.util.NoSuchElementException
|
||||
case m: NoSuchElementException ⇒ 0
|
||||
}
|
||||
val result2 = Await.result(failedFilter, 1 second)
|
||||
result2 must be(0) //Can only be 0 when there was a MatchError
|
||||
|
|
@ -258,7 +259,8 @@ class FutureDocSpec extends AkkaSpec {
|
|||
|
||||
"demonstrate usage of fold" in {
|
||||
//#fold
|
||||
val futures = for (i ← 1 to 1000) yield Future(i * 2) // Create a sequence of Futures
|
||||
// Create a sequence of Futures
|
||||
val futures = for (i ← 1 to 1000) yield Future(i * 2)
|
||||
val futureSum = Future.fold(futures)(0)(_ + _)
|
||||
Await.result(futureSum, 1 second) must be(1001000)
|
||||
//#fold
|
||||
|
|
@ -266,7 +268,8 @@ class FutureDocSpec extends AkkaSpec {
|
|||
|
||||
"demonstrate usage of reduce" in {
|
||||
//#reduce
|
||||
val futures = for (i ← 1 to 1000) yield Future(i * 2) // Create a sequence of Futures
|
||||
// Create a sequence of Futures
|
||||
val futures = for (i ← 1 to 1000) yield Future(i * 2)
|
||||
val futureSum = Future.reduce(futures)(_ + _)
|
||||
Await.result(futureSum, 1 second) must be(1001000)
|
||||
//#reduce
|
||||
|
|
@ -290,8 +293,9 @@ class FutureDocSpec extends AkkaSpec {
|
|||
val msg1 = -1
|
||||
//#try-recover
|
||||
val future = akka.pattern.ask(actor, msg1) recoverWith {
|
||||
case e: ArithmeticException ⇒ Future.successful(0)
|
||||
case foo: IllegalArgumentException ⇒ Future.failed[Int](new IllegalStateException("All br0ken!"))
|
||||
case e: ArithmeticException ⇒ Future.successful(0)
|
||||
case foo: IllegalArgumentException ⇒
|
||||
Future.failed[Int](new IllegalStateException("All br0ken!"))
|
||||
}
|
||||
//#try-recover
|
||||
Await.result(future, 1 second) must be(0)
|
||||
|
|
|
|||
|
|
@ -50,10 +50,16 @@ object HttpServer {
|
|||
val rsp = request match {
|
||||
case Request("GET", "ping" :: Nil, _, _, headers, _) ⇒
|
||||
OKResponse(ByteString("<p>pong</p>"),
|
||||
request.headers.exists { case Header(n, v) ⇒ n.toLowerCase == "connection" && v.toLowerCase == "keep-alive" })
|
||||
request.headers.exists {
|
||||
case Header(n, v) ⇒
|
||||
n.toLowerCase == "connection" && v.toLowerCase == "keep-alive"
|
||||
})
|
||||
case req ⇒
|
||||
OKResponse(ByteString("<p>" + req.toString + "</p>"),
|
||||
request.headers.exists { case Header(n, v) ⇒ n.toLowerCase == "connection" && v.toLowerCase == "keep-alive" })
|
||||
request.headers.exists {
|
||||
case Header(n, v) ⇒
|
||||
n.toLowerCase == "connection" && v.toLowerCase == "keep-alive"
|
||||
})
|
||||
}
|
||||
socket write OKResponse.bytes(rsp).compact
|
||||
if (!rsp.keepAlive) socket.close()
|
||||
|
|
@ -64,7 +70,8 @@ object HttpServer {
|
|||
//#actor-companion
|
||||
|
||||
//#request-class
|
||||
case class Request(meth: String, path: List[String], query: Option[String], httpver: String, headers: List[Header], body: Option[ByteString])
|
||||
case class Request(meth: String, path: List[String], query: Option[String],
|
||||
httpver: String, headers: List[Header], body: Option[ByteString])
|
||||
case class Header(name: String, value: String)
|
||||
//#request-class
|
||||
|
||||
|
|
@ -118,13 +125,15 @@ object HttpIteratees {
|
|||
|
||||
//#read-path
|
||||
def readPath = {
|
||||
def step(segments: List[String]): IO.Iteratee[List[String]] = IO peek 1 flatMap {
|
||||
case PATH ⇒ IO drop 1 flatMap (_ ⇒ readUriPart(pathchar) flatMap (segment ⇒ step(segment :: segments)))
|
||||
case _ ⇒ segments match {
|
||||
case "" :: rest ⇒ IO Done rest.reverse
|
||||
case _ ⇒ IO Done segments.reverse
|
||||
def step(segments: List[String]): IO.Iteratee[List[String]] =
|
||||
IO peek 1 flatMap {
|
||||
case PATH ⇒ IO drop 1 flatMap (_ ⇒ readUriPart(pathchar) flatMap (
|
||||
segment ⇒ step(segment :: segments)))
|
||||
case _ ⇒ segments match {
|
||||
case "" :: rest ⇒ IO Done rest.reverse
|
||||
case _ ⇒ IO Done segments.reverse
|
||||
}
|
||||
}
|
||||
}
|
||||
step(Nil)
|
||||
}
|
||||
//#read-path
|
||||
|
|
@ -140,14 +149,17 @@ object HttpIteratees {
|
|||
val alpha = Set.empty ++ ('a' to 'z') ++ ('A' to 'Z') map (_.toByte)
|
||||
val digit = Set.empty ++ ('0' to '9') map (_.toByte)
|
||||
val hexdigit = digit ++ (Set.empty ++ ('a' to 'f') ++ ('A' to 'F') map (_.toByte))
|
||||
val subdelim = Set('!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=') map (_.toByte)
|
||||
val subdelim = Set('!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=') map
|
||||
(_.toByte)
|
||||
val pathchar = alpha ++ digit ++ subdelim ++ (Set(':', '@') map (_.toByte))
|
||||
val querychar = pathchar ++ (Set('/', '?') map (_.toByte))
|
||||
|
||||
def readUriPart(allowed: Set[Byte]): IO.Iteratee[String] = for {
|
||||
str ← IO takeWhile allowed map ascii
|
||||
pchar ← IO peek 1 map (_ == PERCENT)
|
||||
all ← if (pchar) readPChar flatMap (ch ⇒ readUriPart(allowed) map (str + ch + _)) else IO Done str
|
||||
all ← if (pchar) readPChar flatMap (ch ⇒ readUriPart(allowed) map
|
||||
(str + ch + _))
|
||||
else IO Done str
|
||||
} yield all
|
||||
|
||||
def readPChar = IO take 3 map {
|
||||
|
|
@ -173,15 +185,18 @@ object HttpIteratees {
|
|||
value ← IO takeUntil CRLF flatMap readMultiLineValue
|
||||
} yield Header(ascii(name), ascii(value))
|
||||
|
||||
def readMultiLineValue(initial: ByteString): IO.Iteratee[ByteString] = IO peek 1 flatMap {
|
||||
case SP ⇒ IO takeUntil CRLF flatMap (bytes ⇒ readMultiLineValue(initial ++ bytes))
|
||||
case _ ⇒ IO Done initial
|
||||
}
|
||||
def readMultiLineValue(initial: ByteString): IO.Iteratee[ByteString] =
|
||||
IO peek 1 flatMap {
|
||||
case SP ⇒ IO takeUntil CRLF flatMap (
|
||||
bytes ⇒ readMultiLineValue(initial ++ bytes))
|
||||
case _ ⇒ IO Done initial
|
||||
}
|
||||
//#read-headers
|
||||
|
||||
//#read-body
|
||||
def readBody(headers: List[Header]) =
|
||||
if (headers.exists(header ⇒ header.name == "Content-Length" || header.name == "Transfer-Encoding"))
|
||||
if (headers.exists(header ⇒ header.name == "Content-Length" ||
|
||||
header.name == "Transfer-Encoding"))
|
||||
IO.takeAll map (Some(_))
|
||||
else
|
||||
IO Done None
|
||||
|
|
@ -210,7 +225,8 @@ object OKResponse {
|
|||
date ++= ByteString(new java.util.Date().toString) ++= CRLF ++=
|
||||
server ++= CRLF ++=
|
||||
contentLength ++= ByteString(rsp.body.length.toString) ++= CRLF ++=
|
||||
connection ++= (if (rsp.keepAlive) keepAlive else close) ++= CRLF ++= CRLF ++= rsp.body result
|
||||
connection ++= (if (rsp.keepAlive) keepAlive else close) ++= CRLF ++=
|
||||
CRLF ++= rsp.body result
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,7 +32,8 @@ class RemoteDeploymentDocSpec extends AkkaSpec("""
|
|||
|
||||
"demonstrate programmatic deployment" in {
|
||||
//#deploy
|
||||
val ref = system.actorOf(Props[SampleActor].withDeploy(Deploy(scope = RemoteScope(address))))
|
||||
val ref = system.actorOf(Props[SampleActor].
|
||||
withDeploy(Deploy(scope = RemoteScope(address))))
|
||||
//#deploy
|
||||
ref.path.address must be(address)
|
||||
ref ! "test"
|
||||
|
|
|
|||
|
|
@ -22,8 +22,10 @@ class RouterDocSpec extends AkkaSpec {
|
|||
|
||||
//#dispatchers
|
||||
val router: ActorRef = system.actorOf(Props[MyActor]
|
||||
.withRouter(RoundRobinRouter(5, routerDispatcher = "router")) // “head” will run on "router" dispatcher
|
||||
.withDispatcher("workers")) // MyActor workers will run on "workers" dispatcher
|
||||
// “head” will run on "router" dispatcher
|
||||
.withRouter(RoundRobinRouter(5, routerDispatcher = "router"))
|
||||
// MyActor workers will run on "workers" dispatcher
|
||||
.withDispatcher("workers"))
|
||||
//#dispatchers
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,8 +66,8 @@ class ParentActor extends Actor {
|
|||
//#randomRouter
|
||||
case "smr" ⇒
|
||||
//#smallestMailboxRouter
|
||||
val smallestMailboxRouter =
|
||||
context.actorOf(Props[PrintlnActor].withRouter(SmallestMailboxRouter(5)), "router")
|
||||
val smallestMailboxRouter = context.actorOf(Props[PrintlnActor].
|
||||
withRouter(SmallestMailboxRouter(5)), "router")
|
||||
1 to 10 foreach {
|
||||
i ⇒ smallestMailboxRouter ! i
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,7 +40,8 @@ class TestKitUsageSpec
|
|||
val randomTail = Random.nextInt(10)
|
||||
val headList = Seq().padTo(randomHead, "0")
|
||||
val tailList = Seq().padTo(randomTail, "1")
|
||||
val seqRef = system.actorOf(Props(new SequencingActor(testActor, headList, tailList)))
|
||||
val seqRef =
|
||||
system.actorOf(Props(new SequencingActor(testActor, headList, tailList)))
|
||||
|
||||
override def afterAll {
|
||||
system.shutdown()
|
||||
|
|
|
|||
|
|
@ -49,7 +49,8 @@ object ZeromqDocSpec {
|
|||
val timestamp = System.currentTimeMillis
|
||||
|
||||
// use akka SerializationExtension to convert to bytes
|
||||
val heapPayload = ser.serialize(Heap(timestamp, currentHeap.getUsed, currentHeap.getMax)).get
|
||||
val heapPayload = ser.serialize(Heap(timestamp, currentHeap.getUsed,
|
||||
currentHeap.getMax)).get
|
||||
// the first frame is the topic, second is the message
|
||||
pubSocket ! ZMQMessage(Seq(Frame("health.heap"), Frame(heapPayload)))
|
||||
|
||||
|
|
@ -64,19 +65,24 @@ object ZeromqDocSpec {
|
|||
//#logger
|
||||
class Logger extends Actor with ActorLogging {
|
||||
|
||||
ZeroMQExtension(context.system).newSocket(SocketType.Sub, Listener(self), Connect("tcp://127.0.0.1:1235"), Subscribe("health"))
|
||||
ZeroMQExtension(context.system).newSocket(SocketType.Sub, Listener(self),
|
||||
Connect("tcp://127.0.0.1:1235"), Subscribe("health"))
|
||||
val ser = SerializationExtension(context.system)
|
||||
val timestampFormat = new SimpleDateFormat("HH:mm:ss.SSS")
|
||||
|
||||
def receive = {
|
||||
// the first frame is the topic, second is the message
|
||||
case m: ZMQMessage if m.firstFrameAsString == "health.heap" ⇒
|
||||
val Heap(timestamp, used, max) = ser.deserialize(m.payload(1), classOf[Heap]).get
|
||||
log.info("Used heap {} bytes, at {}", used, timestampFormat.format(new Date(timestamp)))
|
||||
val Heap(timestamp, used, max) = ser.deserialize(m.payload(1),
|
||||
classOf[Heap]).get
|
||||
log.info("Used heap {} bytes, at {}", used,
|
||||
timestampFormat.format(new Date(timestamp)))
|
||||
|
||||
case m: ZMQMessage if m.firstFrameAsString == "health.load" ⇒
|
||||
val Load(timestamp, loadAverage) = ser.deserialize(m.payload(1), classOf[Load]).get
|
||||
log.info("Load average {}, at {}", loadAverage, timestampFormat.format(new Date(timestamp)))
|
||||
val Load(timestamp, loadAverage) = ser.deserialize(m.payload(1),
|
||||
classOf[Load]).get
|
||||
log.info("Load average {}, at {}", loadAverage,
|
||||
timestampFormat.format(new Date(timestamp)))
|
||||
}
|
||||
}
|
||||
//#logger
|
||||
|
|
@ -84,17 +90,20 @@ object ZeromqDocSpec {
|
|||
//#alerter
|
||||
class HeapAlerter extends Actor with ActorLogging {
|
||||
|
||||
ZeroMQExtension(context.system).newSocket(SocketType.Sub, Listener(self), Connect("tcp://127.0.0.1:1235"), Subscribe("health.heap"))
|
||||
ZeroMQExtension(context.system).newSocket(SocketType.Sub,
|
||||
Listener(self), Connect("tcp://127.0.0.1:1235"), Subscribe("health.heap"))
|
||||
val ser = SerializationExtension(context.system)
|
||||
var count = 0
|
||||
|
||||
def receive = {
|
||||
// the first frame is the topic, second is the message
|
||||
case m: ZMQMessage if m.firstFrameAsString == "health.heap" ⇒
|
||||
val Heap(timestamp, used, max) = ser.deserialize(m.payload(1), classOf[Heap]).get
|
||||
val Heap(timestamp, used, max) = ser.deserialize(m.payload(1),
|
||||
classOf[Heap]).get
|
||||
if ((used.toDouble / max) > 0.9) count += 1
|
||||
else count = 0
|
||||
if (count > 10) log.warning("Need more memory, using {} %", (100.0 * used / max))
|
||||
if (count > 10) log.warning("Need more memory, using {} %",
|
||||
(100.0 * used / max))
|
||||
}
|
||||
}
|
||||
//#alerter
|
||||
|
|
@ -109,7 +118,8 @@ class ZeromqDocSpec extends AkkaSpec("akka.loglevel=INFO") {
|
|||
|
||||
//#pub-socket
|
||||
import akka.zeromq.ZeroMQExtension
|
||||
val pubSocket = ZeroMQExtension(system).newSocket(SocketType.Pub, Bind("tcp://127.0.0.1:21231"))
|
||||
val pubSocket = ZeroMQExtension(system).newSocket(SocketType.Pub,
|
||||
Bind("tcp://127.0.0.1:21231"))
|
||||
//#pub-socket
|
||||
|
||||
//#sub-socket
|
||||
|
|
@ -121,11 +131,13 @@ class ZeromqDocSpec extends AkkaSpec("akka.loglevel=INFO") {
|
|||
case _ ⇒ //...
|
||||
}
|
||||
}))
|
||||
val subSocket = ZeroMQExtension(system).newSocket(SocketType.Sub, Listener(listener), Connect("tcp://127.0.0.1:21231"), SubscribeAll)
|
||||
val subSocket = ZeroMQExtension(system).newSocket(SocketType.Sub,
|
||||
Listener(listener), Connect("tcp://127.0.0.1:21231"), SubscribeAll)
|
||||
//#sub-socket
|
||||
|
||||
//#sub-topic-socket
|
||||
val subTopicSocket = ZeroMQExtension(system).newSocket(SocketType.Sub, Listener(listener), Connect("tcp://127.0.0.1:21231"), Subscribe("foo.bar"))
|
||||
val subTopicSocket = ZeroMQExtension(system).newSocket(SocketType.Sub,
|
||||
Listener(listener), Connect("tcp://127.0.0.1:21231"), Subscribe("foo.bar"))
|
||||
//#sub-topic-socket
|
||||
|
||||
//#unsub-topic-socket
|
||||
|
|
|
|||
|
|
@ -93,7 +93,7 @@ by Actors:
|
|||
akka {
|
||||
actor {
|
||||
debug {
|
||||
# enable DEBUG logging of all AutoReceiveMessages (Kill, PoisonPill and the like)
|
||||
# enable DEBUG logging of all AutoReceiveMessages (Kill, PoisonPill et.c.)
|
||||
autoreceive = on
|
||||
}
|
||||
}
|
||||
|
|
@ -148,7 +148,8 @@ If you want to see all messages that are sent through remoting at DEBUG log leve
|
|||
|
||||
akka {
|
||||
remote {
|
||||
# If this is "on", Akka will log all outbound messages at DEBUG level, if off then they are not logged
|
||||
# If this is "on", Akka will log all outbound messages at DEBUG level,
|
||||
# if off then they are not logged
|
||||
log-sent-messages = on
|
||||
}
|
||||
}
|
||||
|
|
@ -160,7 +161,8 @@ If you want to see all messages that are received through remoting at DEBUG log
|
|||
|
||||
akka {
|
||||
remote {
|
||||
# If this is "on", Akka will log all inbound messages at DEBUG level, if off then they are not logged
|
||||
# If this is "on", Akka will log all inbound messages at DEBUG level,
|
||||
# if off then they are not logged
|
||||
log-received-messages = on
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -419,7 +419,13 @@ implementation called :class:`TestProbe`. The functionality is best explained
|
|||
using a small example:
|
||||
|
||||
.. includecode:: code/docs/testkit/TestkitDocSpec.scala
|
||||
:include: imports-test-probe,my-double-echo,test-probe
|
||||
:include: imports-test-probe
|
||||
|
||||
.. includecode:: code/docs/testkit/TestkitDocSpec.scala
|
||||
:include: my-double-echo
|
||||
|
||||
.. includecode:: code/docs/testkit/TestkitDocSpec.scala
|
||||
:include: test-probe
|
||||
|
||||
Here a the system under test is simulated by :class:`MyDoubleEcho`, which is
|
||||
supposed to mirror its input to two outputs. Attaching two test probes enables
|
||||
|
|
@ -458,7 +464,10 @@ concerning volume and timing of the message flow while still keeping the
|
|||
network functioning:
|
||||
|
||||
.. includecode:: code/docs/testkit/TestkitDocSpec.scala
|
||||
:include: test-probe-forward-actors,test-probe-forward
|
||||
:include: test-probe-forward-actors
|
||||
|
||||
.. includecode:: code/docs/testkit/TestkitDocSpec.scala
|
||||
:include: test-probe-forward
|
||||
|
||||
The ``dest`` actor will receive the same message invocation as if no test probe
|
||||
had intervened.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue