I would like to know if it's possible (and how) to get an akka actor to receive messages from stdin. Essentially, the idea would be for every line of input to be sent as a message to the actor, e.g.
开发者_开发技巧> myprogram
DO X
DO Y
...
and then to have the actor receive messages "DO X", "DO Y", etc.
Is there a standard solution to do this?
I guess one way would be to do this:
spawn {
while(in.available) {
actor ! in.readLine
}
}
But then I'd have two actors (or one actor-based task and one actor) and I'd be using blocking IO (is that safe with actors, by the way?)... Also, it makes it harder to control the spawn block (e.g. to kill the task).
Added further follow ups from OP
I have a couple follow ups, if you will allow me...
Is there a performance hit using this solution (i.e. does
CamelServiceManager
start a lot of things? HTTP server, etc.)?Got a good tutorial for beginners? I started reading Camel from the official Akka documentation, but it seems to assume more knowledge of Camel than I currently possess. For instance, I couldn't figure out how to use a custom
java.io.InputStream
asendpointUri
.
You could use akka-camel together with the camel-stream component to let actors receive messages from stdin. Here's a working example:
import akka.actor.Actor
import akka.camel.{Message, CamelServiceManager, Consumer}
object Example extends App {
CamelServiceManager.startCamelService
Actor.actorOf[ExampleConsumer].start
}
class ExampleConsumer extends Actor with Consumer {
def endpointUri = "stream:in"
def receive = {
case msg: Message => println("received %s" format msg.bodyAs[String])
}
}
Update: Answers to the follow-up questions
- The
CamelServiceManager.startCamelService
method starts aCamelContext
and two Akka actors that register newly startedConsumer
actor endpoints at theCamelContext
. No HTTP server is started. - Good introductions to Apache Camel are Apache Camel: Integration Nirvana article and chapter 1 of the Camel in Action book. The Appendix E of Camel in Action is an introduction to akka-camel.
- Setting a custom
InputStream
at the endpoint URI is currently not possible with the camel-stream component.
精彩评论