1. Introduction to Akka & Introduction to Common APIs

Introduction to Akka

Akka is a toolkit for building high-concurrency, distributed and fault-tolerant applications on the Java virtual machine platform. Akka is written in Scala language, and it also provides development interfaces for Scala and Java.

Akka can be used in two different ways

  • In the form of a library: used in web applications, placed in WEB-INF/lib or placed in the classpath as a normal Jar package.
  • In the form of a microkernel: You can put your application into a separate kernel. I have a main class to initialize the Actor system.

Several features of Akka

  1. Easy to build parallel and distributed applications (Simple Concurrency & Distribution)

    Akka adopts asynchronous communication and distributed architecture when designing, and abstracts the upper layer, such as Actors, Futures, STM, etc.

  2. Fault tolerance (Resilient by Design)

    The system has self-healing ability, and monitors both locally and remotely.

  3. High Performance

    In a single machine, 50 million messages can be sent per second. The memory footprint is small, 2.5 million actors can be stored in 1GB of memory.

  4. Elastic, Decentralized (Elastic — Decentralized)

    Self-adaptively responsible for balancing, routing, partitioning, and configuration

  5. Extensible

    You can use the Akka extension package for extension.

In the world of Akka, there is only one content that needs to be learned and managed, with high cohesion and high consistency semantics. Akka is a highly scalable software, not only in terms of performance, but also in the size of the application it is applicable to. The core of Akka, Akka-actor is very small and can be easily put into your application to provide the asynchronous lock-free parallel functions you need without any trouble. You can choose any part of Akka to integrate into your application, or you can use the complete package-Akka microkernel, which is an independent container that can directly deploy your Akka application. With the increasing number of CPU cores, even if you only use a computer, Akka can also be used as a choice to provide excellent performance. Akka also provides a variety of concurrency paradigms, allowing users to choose the right tool to complete the work.

Akka is simple to use

Use IDEA+Maven to build Akka development environment.

  1. Import Maven dependencies

    <properties>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
            <encoding>UTF-8</encoding>
            <scala.version>2.11.8</scala.version>
            <scala.compat.version>2.11</scala.compat.version>
            <akka.version>2.3.6</akka.version>
        </properties>
    
        <dependencies>
            <!-- 添加scala的依赖 -->
            <dependency>
                <groupId>org.scala-lang</groupId>
                <artifactId>scala-library</artifactId>
                <version>${
          
          scala.version}</version>
            </dependency>
            <!-- 添加akka的actor依赖 -->
            <dependency>
                <groupId>com.typesafe.akka</groupId>
                <artifactId>akka-actor_${
          
          scala.compat.version}</artifactId>
                <version>${
          
          akka.version}</version>
            </dependency>
            <!-- 多进程之间的Actor通信 -->
            <dependency>
                <groupId>com.typesafe.akka</groupId>
                <artifactId>akka-remote_${
          
          scala.compat.version}</artifactId>
                <version>${
          
          akka.version}</version>
            </dependency>
        </dependencies>
    
  2. Java implements Actor Demo

    /**
     * @author li.pan
     * @version 1.0.0
     * @Description TODO
     * @createTime 2020年12月22日 20:18:00
     */
    public class JavaPongActor extends AbstractActor {
          
          
    
        /**
         * AbstractActor 类有一个 receive 方法,其子类必须实现这个方法或是通过构造函数调用该方法。
         *
         * @return 返回的类型是PartialFunction(偏函数), 这个类型来自Scala API。在Java中
         * Akka为我们提供了一个抽象的构造方法类ReceiveBuilder,用于生成 PartialFunction 作为返回值。
         */
        @Override
        public PartialFunction receive() {
          
          
            return ReceiveBuilder
                    // matchEquals和matchAny用来匹配消息
                    .matchEquals("Ping", s ->
                            sender().tell("Pong", ActorRef.noSender()))
                    .match(String.class, s ->
                            System.out.println("It's a string: " + s))
                    .matchAny(x ->
                            sender().tell(
                                    new Status.Failure(new Exception("unknown message")), self()))
                    .build();
        }
    }
    

    The above Java code shows how to use the corresponding Java API in Akka. The meaning of each specific API is as follows:

    method meaning
    Receive The AbstractActor class has a receive method, and its subclasses must implement this method or call the method through the constructor. The type returned by the receive method is PartialFunction, which comes from the Scala API. In Java, there is no native method to construct Scala PartialFunction (partial function), so Akka provides us with an abstract constructor class
    ReceiveBuilder Mainly use the Build method to return PartialFunction
    Match Similar to pattern matching in Scala, it is used for message matching:
    match(class, function) : describes how to respond to any examples of this type that have not yet been matched.
    match(String.class, s -> {if(s.equals("Ping")) respondToPing(s);})
    match(class, predicate, function) : Describes how to respond to a specific type of message where the predicate condition function is true.
    match(String.class, s -> s.equals("Ping"), s -> respondToPing(s))
    matchEquals(object, function) : describes how to respond to a message equal to the first parameter passed in.
    matchEquals("Ping", s -> respondToPing(s))
    matchAny(function) : This function matches all unmatched messages. Generally speaking, the best practice is to return error messages, or at least log the error messages to help debug errors during the development process.
    Sender Return the response to the received message. The object of the response may be an Actor or a request from outside the Actor system.
    Tell The sender() function returns an ActorRef. In the above example, we called sender().tell(). tell() is the most basic one-way message transmission mode. The first parameter is the message we want to send to the other party's mailbox. The second parameter is the sender that you want the other Actor to see.
    Ask Send a message to the Actor and return a Future. When the Actor returns a response, the Future will be completed. No message will be returned to the sender's mailbox.
    Forward Send the received message to another Actor. All responses sent to sender() will be returned to the sender of the original message.
    Pipe Used to return the result of the Future to sender() or another Actor. If you are using Ask or processing a Future, then using Pipe can correctly return the result of the Future.
  3. Scala implements Actor Demo

    class ScalaPongActor extends Actor {
          
          
      override def receive: Receive = {
          
          
        case "Ping" => sender() ! "Pong"
        case _ => sender() ! Status.Failure(new Exception("unknown message"))
      }
    }
    

    The above code uses the Scala language to implement a simple Actor. Most of its API has the same meaning as in Java. Some of the differences in use are as follows:

    method meaning
    Receive Override the receive method of the base class in Actor. And returns a PartialFunction. It should be noted that the return type of the receive method is Receive. Receive is just a type of definition, which means scala.PartialFunction[scala.Any, scala.Unit].
    Sender Return the response to the received message. The object of the response may be an Actor or a request from outside the Actor system.
    ! In Scala, the tell method is called by "!". In Scala, the message sender is implicitly passed in, so we don't need to explicitly pass in the reference of the message sender. In the method signature of the tell method "!", there is an implicit ActorRef parameter. If the tell method is called outside the Actor, the default value of this parameter will be set to noSender. Here is the signature of the method:
    def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit
    ? "?" in scala stands for ask.
    Failure When an unknown message is received, akka.actor.Status.Failure is returned. The Actor itself will not return Failure by itself under any circumstances (even if the Actor itself has an error). Therefore, if we want to notify the sender of an error that has occurred, then we must actively send a Failure to the other party. Sending it back to Failure will cause the requester's Future to be marked as failed.

    Another thing to note is that there is an implicit variable self in Actor in Scala, and Actor gets the value of the message sender through self. Therefore, the message sender of the tell method in Actor is always self.

    implicit final val self = context.self
    

Pay attention to the official account, 数据工匠记and focus on the offline and real-time technical dry goods in the big data field to share regularly! Personal website www.lllpan.top
Insert picture description here

Guess you like

Origin blog.csdn.net/lp284558195/article/details/111567913