I was under the impression that the only way to communicate with an Akka Actor from outside the ActorSystem was via Inbox. However I just found this snippet from Akka's own documentation which shows:
greeter.tell(new WhoToGreet("akka"), ActorRef.noSender());
inbox.send(greeter, new Greet());
So which is it? Is it in fact possible to directly tell an Actor from the outside world, or did Typesafe have a careless intern writing their documentation for them?!?
If it is possible, then when should you do this, and when should you use Inbox? For instance, is one method "fire-and-forget" asynchronous/non-blocking and the other synchronous/blocking?
Inbox is part of the relatively recent Actor DSL API that is "some nice sugar on top of the usual ways to create actors". You can either use the standard way to create / communicate with actors or use the Actor DSL. They are both async. The Actor DSL is nice for creating one-off actors whose lifetime is one method. The advantage of the DSL syntax is a bit more evident in Scala.
You can safely send messages from outside an actor. Akka will fill in a dummy sender. You just won't be able to receive any replies (though you can use an ask for that).
Related
Within Java you can create an Observer-Observable set of classes in which the Observable can call the Observer. You can also in java explicitly reference an owning class instance in a child instance of another class and call the owning class instance's public functions.
Which is the better approach to take? Which is more beneficial in different scenarios, one example being Multi-Threading?
The Observer Pattern should be used whenever you don't know or don't care who is observing you. This is the key-concept in event-driven programming. You don't have any control of who is observing or what they do when you broadcast your events. Like you already mentioned in your comments, this is great for decoupling classes.
An example of a usage could be in a plugin-architecture:
You write a basic mail-server that broadcasts whenever a mail is received. You could then have a spam-plugin that validates the incoming mail, an auto-reply service that sends a reply, a forward service that redirects the mail and so on. Your plain mail server (the observable) doesn't know anything about spam, replies or forwarding. It just shouts out "Hey, a new mail is here" not knowing if anyone is listening. Then each of the plugins (the observers) does their own special thing, not knowing anything about each other. This system is very flexible and could easily be extended.
But the flexibility provided by the Observer Pattern is a two-edged sword. In the mail-server example, each plugin handles the incoming mail in total isolation from each other. This makes it impossible to setup rules like "don't reply or forward spam" because the observers doesn't know about each other - and even if they did, they wouldn't know in what order they are executed or has completed. So for the basic mail-server to solve this problem, It'll need to have references to the instances that does the spam/reply/forward actions.
So the Observer Pattern provides flexibility. You could easily add a new anti-virus plugin later, without having to modify your plain mail server code. The cost of this flexibility is loss of control of the flow of actions.
The reference approach gives you total control of the flow of actions. However you would need to modify your plain mail server code if you ever need to add support for an anti-virus plugin.
I hope this example gives you some ideas of the pros and cons of each approach.
In regards to multi-threading, one approach isn't favorable over the other.
I'm currently in the process of making a pretty large Akka based Java application and I'm running into a couple issues that bug me to no end.
My current package layout looks kinda like this:
My Mobile class serving as the supervisor of the actors inside the actors package.
Since I don't want to create a new set of Actors for every HttpClient and Account, I pass those around in message objects, which are stored in the messages package, together with the endpoint ActorRef that receives the final result. This does however create a very cluttered messages package with a different message for each actor. Eg. MobileForActor1, Actor1ForMobile, MobileForActor2 etc. Now my question is, is there a Convention to use for this sort of stuff that deals with this problem and is my structure (Mobile->Actor1->Mobile->Actor2->etc.) the way Akka wants it to be or do I have to just sort of waterfall the messages (Mobile->Actor1->Actor2->etc.)?
Right now I'm sending a ConnectMessage to my Mobile actor which then sends it to Actor1, Actor1 processes it and sends a new message back to Mobile, Mobile sends that response then to Actor2 and the cycle continues with a new message being created based on the old message. Eg. new Message2(message1.foo, message1.bar, message1.baz, newComputatedResult, newComputatedResult2, etc);
Is this good practice or should I include the old instance (which may contain info that isn't useful anymore) and include the new stuff? Eg. new Message2(message1, newComputatedResult, newComputatedResult2, etc);
Or should I do something completely different?
I thought about using TypedActors but those require the use of a waterfall pattern and I don't know how I would pass on the ActorRef of the listener that wants to receive the final result.
I hope I made myself understandable enough because English is not my maiden languages and that the question is clear to everyone.
I'm a beginning Akka developer and love the idea but since the documentation doesn't cover this very well, I figured this would be the best place to ask. Thanks for reading!
I will venture a few comments in response to this because I've dealt with the same issues in my learning curve of Akka. I think you're asking for some rules of thumb so mine are contained herein.
First, creating actors is incredibly cheap; they are very lightweight. So, why not create one for each HttpClient and Account and give them suitable names derived from their identity? This also avoids you having to pass them around as much, probably, decluttering your code.
Second, keep your message names short, focused and starting with a verb. Each message should tell the actor to do something so you want the name to reflect that by using a verb.
Third, sets of messages go with the actor. I usually declare them in the actor class's companion object so that using them is like ActorClass.MessageName unless it is within ActorClass and then it is just MessageName.
Fourth, append a counter to the name of an actor. I often just combine a counter (use AtomicInteger) with the name of the type (Car-1, Car-2, etc.).
If the hierarchy is important to you, I would recommend only appending the parent actor to the name. Something like Phone-1-in-Car-7 meaning Phone-1 is contained within Car-7. You can then assemble the hierarchy both programmatically and manually by following the parent links.
I think "Message" in ConnectMessage is redundant. Just make the message name be "Connect" or even better "ConnectToThing" (whatever Thing is, if that's relevant).
I wouldn't compound your message names too much like you're suggesting with Message2. Use the minimal amount of information to be useful to whomever is going to read those names. I think the lack of response to this may have resulted from this part of your question. I found it confusing as a lot of detail is missing.
Hope this helps.
I am implementing my own custom component and I have found that I am going to need two use cases for consumers:
The first one would be trying to get N number of available messages every so often (Polling Consumer)
The second one would be a subscriber consumer that gets messages when they are available.
My main question is if it possible to implement these two types. I have been trying to write some code, but it seems that if you are developing a PollingConsumer you cannot implement another type. Also, if it is possible, is there any example, article or guide about how to do this? I have been looking for it for nothing came up.
Thanks!
There is two consumer kind in Camel (eg from the EIP book)
Consumer
PollingConsumer
Its the former that is used in the Camel routes. And the latter is used when you use it explicit or when using ConsumerTemplate, to use the receive methods.
A Camel component is able to adapt a Consumer to a PollingConsumer out of the box.
So it depends if you want to build a Camel component that are used in routes, you can just create a consumer. And have it able to do both poll and subscribe. When you have the data, then create an Exchange and call the processor to route it.
For documentation then check the Camel website, and/or chapter 11 in the Camel in Action book which covers creating custom components.
I am developing a distributed system which consists of different components (services) which are loosely (asynchronously) coupled via JMS (ActiveMQ).
Thus I do not want to reinvent the wheel, I am looking for a (well) known protocol / library that facilitates remote procedure calls inbetween these components and helps me deal with method interfaces.
So let's decompose the problem I am already solving right now via dirty solutions:
A consumer component want's to call a service, thus it constructs a request string (hand-written and dirty)
The request string is than compressed an put into a JMS message (dirty aswell)
The request message is than transmitted via JMS and routing mechanisms (that part is ok)
The service first of all needs to decompress and parse the request string, to identify the right method (dirty)
The method gets called and the reply goes like #2 - #4.
So that looks pretty much like SOAP, whilst I think that SOAP is to heavy for my application and further I am not using HTTP at all. Given that I was thinking that one might be able to deconstruct the problem into different components.
Part A: HTTP is replaced by JMS (that one is okay)
Part B: XML is replaced by something more lightweight (alright, MessagePack comes in handy here)
Part C: Mechanism to parse request/reply string to identify operation name and parameter values (that one is the real problem here)
I was looking into MessagePack, ProtocolBuffers, Thrift and so forth, but what I don't like about them is that they introduce their own way of handling the actual (TCP) communication. And bypass my already sophisticated JMS infrastructure (which also handles load balancing and stuff).
To further elaborate Part C above, this is how I am currently handling it: Right know I would do something like the following if a consumer would call a service, let's assume the service takes a text and replies keywords. I would have the consumer create a JMS message and transmit it (via ActiveMQ) to the service. The message would contain:
Syntax: OPERATION_NAME [PARAMETERS]
Method: GET_ALL_KEYWORDS [String text] returns [JSON String[] keywords]
Example Request: GET_ALL_KEYWORDS "Hello world, this is my input text..."
Example Reply: ["hello", "world", "text"]
Needless to say that it feels like hacked-together. The problem I see is if I would be to change the method interface by adding or deleting parameters, I would have to check all the request/reply string construction/deconstructions to syncronize the changes. That is pretty errorprone. I'd rather have the library construct the right request/reply syntax by looking at a java interface and throwing real exceptions on runtime if I do mess up stuff, like "Protocol Exception: Mandatory parameter not set" or something...
Any projects/libs known for that?
Requirements would be
It's small and lightweight and fast.
It's implemented in JAVA
It doesn't serve too many purposes (like some fullblown framework e.g. Spring)
I think this Spring package is what you're looking for. See JmsInvokerProxyFactoryBean and related classes.
From the javadoc:
FactoryBean for JMS invoker proxies. Exposes the proxied service for
use as a bean reference, using the specified service interface.
Serializes remote invocation objects and deserializes remote
invocation result objects. Uses Java serialization just like RMI, but
with the JMS provider as communication infrastructure.
Hey guys,
I'm using GWT to code a simple multiplayer board game.
And while I was coding the question came up to my mind:
At first I though my client could simply communicate with the server via RemoteServices calls, so if a client wanted to connect to a game he could do as follows:
joinGame (String playerName, String gameName)
And the server implementation would do the necessary processing with the argument's data.
In other words, I would have lots of RemoteService methods, one for each type of message in the worst case.
I thought of another way, which would be creating a Message class and sub-classing it as needed.
This way, a single remoteService method would be enough:
sendMessage (Message m)
The messages building and interpreting processing too would be done by specialized classes.
Specially the building class could even be put in the gwt-app shared package.
That said,
I can't see the benefits of one or another. Thus I'm not sure if I should do one way or another or even another completely different way.
One vs other, who do you think it is better (has more benefits in the given situation)?
EDIT: A thing I forgot to mention is that one of the factors that made me think of the second (sendMessage) option was that in my application there is a CometServlet that queries game instances to see if there is not sent messages to the client in its own message queue (each client has a message queue).
I prefer the command pattern in this case (something like your sendMessage() concept).
If you have one remote service method that accepts a Command, caching becomes very simple. Batching is also easier to implement in this case. You can also add undo functionality, if that's something you think you may need.
The gwt-dispatch project is a great framework that brings this pattern to GWT.
Messaging takes more programmer time and creates a more obfuscated interface. Using remote service methods is cleaner and faster. If you think there are too many then you can split your service into multiple services. You could have a service for high scores, a service for player records, and a service for the actual game.
The only advantage I can see with messaging is that it could be slightly more portable if you were to move away from a Java RPC environment but that would be a fairly drastic shift.