As you all know, last time in “What’s wrong with a little more technology? We talked about the theoretical knowledge of Actor models in the state of” meng B “. As shown in the figure above, in the Actor model system, there are mainly independent actors (circle in the figure). Communication between actors is realized through messages, in which each Actor has a MailBox to store the received messages. Each Actor maintains its own state.

To tell the truth, talk about Actor model is actually a little drunk weng meaning is not wine, Xiang Zhuang sword to Akka.

The Actor model is still a little confused B, and there is an Akka, what is this? You must have been wondering something.

All right, no idle chatter, please get the little bench ready for our sharing to begin.

1.

Akka is what?

Akka is a library written in Scala to simplify writing fault-tolerant, highly scalable applications of Java and Scala’s Actor model. It has been used successfully in the telecommunications industry. System downtime is almost non-existent (high availability 99.9999999 % only 31 ms per year). Akka is a toolkit and runtime for building highly concurrent, distributed, and fault-tolerant applications on the JAVA Virtual Machine JVM platform. Akka is written in Scala and provides both Scala and JAVA development interfacesFrom Baidu Baike.

Akka is an implementation of the Actor model, which is used to develop an application framework that supports concurrency, fault tolerance and scalability. So Easy!

2.

Akka zha?

Ok, let’s forget the bitter concept, let’s write a super simple HelloWorld to understand the charm of Akka.

Let’s set the goal for HelloWorld: to implement a simple WordCount, break up a sentence by space, and count the number of occurrences of each word.

Step 1: Let’s take a look at the big picture. We are going to use Akka to create HelloWorld.


The second step: the introduction of dependency, considering the convenience of your local test, then put a copy of dependency to you.

< dependencies > < the dependency > < groupId > com. Typesafe. Akka < / groupId > < artifactId > akka - actor_2. 12 < / artifactId > < version > server - < / M5 version > < / dependency > < / dependencies >Copy the code


Step 3: After all this foreshadowing, you can finally get the code to work.

From the heart of the question: actors and actors communicate through messages, so how to define the message entities used for transmission?


From the collision of souls 1: split a sentence Actor, how to define?


Collision of Souls 2: How to define an Actor that counts the number of occurrences of each word?


Ask from heart + soul: how to get together?


Step 4: When the code is done, it’s time to take a look at the glory.

The result is as good as expected! In order to show that I am a responsible sharer, I still need to share all the code so that you can get started quickly.

import akka.actor.*; import java.io.IOException; import java.util.*; Public class WordCountAkka {public static void main(String[] args) { Wordcount ActorSystem ActorSystem = actorSystem.create ("wordcount"); ActorRef SplitActor = actorSystem.actorof ((Props. Create (splitactor.class)),"SplitActor"); ActorRef CountActor = actorSystem.actorof ((Props. Create (countactor.class))),"CountActor"); MSG = new Message(MSG = new Message);"Hello Akka Akka Hello"); SplitActor. Tell (MSG, actorref.nosender ()); //5, Press Enter to exit the application system.out.println (">>> Press ENTER to exit <<<"); System.in.read(); } catch (IOException e) { } finally { actorSystem.terminate(); */ static class SplitActor extends AbstractActor {@override public ReceivecreateReceive() {
            return receiveBuilder().match(Message.class, t -> {
                System.out.println(self() + "Received from" + sender() + "The news:"+ t); // Split data by Spaces String[] Words = string.valueof (t.gettcontent ()).tolowerCase ().split()"\\W+"); // Encapsulate the Message request to CountActor Message MSG = new Message(words); System.out.println(self() +"Send a message:"+ Arrays.toString(words)); ActorSelection countActorRef = getContext().actorSelection("/user/CountActor"); CountActor countactorRef.tell (MSG, self())); }).build(); }} /** * CountActor extends AbstractActor {@override public ReceivecreateReceive() {
            returnReceiveBuilder ().match(message.class, t -> {// Received Message String[] words = (String[]) t.getContent(); System.out.println(self() +"Received from" + sender() + "The news:"+ Arrays.toString(words)); ConutMap = new HashMap<>();for (String word : words) {
                    Integer num = conutMap.get(word);
                    conutMap.put(word, num == null ? 1 : num + 1);
                }
                System.out.println(self() + "The statistical result of the number of occurrences of each word is:"+ conutMap); }).build(); Static class Message {private Object content; public Message(Object content) { this.content = content; } public ObjectgetContent() {
            return content;
        }

        public void setContent(Object content) { this.content = content; }}}Copy the code

In fact, the comments in the code have been written very clearly, but to make you more clear, I will summarize the Akka code development process a little bit.

1, use actorSystem.create ("wordcount") create an Actor system named wordCount; 2. Define XxActor extends AbstractActor and implement createReceive() method to complete business logic processing; ActorSystem. ActorOf ((Props. Create (splitactor.class))),"SplitActor") creates the Actor for business logic processing; GetContext ().actorSelection()"/user/CountActor") select the Actor for the next logical processing; Countactorref. tell(MSG, self()))Copy the code

3.

Ok, with this Akka share and the last Actor model share, you should have some idea of the Actor model. I believe that through the sharing of these two times, we will go deep into the architecture source code, although not to rise to the top, but also good wind by force to send you on qingyun (wu mouth smile).



Naughty, I am looking for an architecture diagram of Flink runtime. Have you found that Actor System plays the role of communication in the whole architecture !!!!

4.

Finally, mainly want to say, “to teach fishing is better than teach them to fish, and try to combine individual in the face of new technology of a research idea, overall understand first sketch, then one by one to understand the 7788, have not seen the new term, new technologies, don’t give up, temporarily blocked, then extracting Resin core source is so, see the Actor, At that time, I did not go into further research, and only now do I begin to understand Actor. But the extracted project architecture has been running smoothly in the business, so if you don’t understand, don’t hinder the whole situation, and it is not a bad way to settle accounts later. In fact, the core idea is simple, “time is tight, the task is heavy, the first to live, the other are white pull!”

Recommended reading:

What’s wrong with a little more technology? A face meng B chat Actor

Mom no longer need to worry, I can not learn big data flink

This tech sunflower gem is really hardcore

And double 叒 yi push explosion