How to get actor messages from stdin?

2019-04-10 22:25发布

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...

  1. Is there a performance hit using this solution (i.e. does CamelServiceManager start a lot of things? HTTP server, etc.)?

  2. 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 as endpointUri.

标签: scala akka actor
1条回答
Melony?
2楼-- · 2019-04-10 23:07

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 a CamelContext and two Akka actors that register newly started Consumer actor endpoints at the CamelContext. 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.
查看更多
登录 后发表回答