AKKA | Hello AKKA

AKKA是可用于设计跨处理器核心和网络的可伸缩、有弹性的系统的开源库。使用Scala语言编写,是基于Actor模型处理并发,提供了Java和Scala的API。下面总结如何基于SpringBoot搭建hello world项目。

第一步引入依赖,

  <properties>
        <akka.version>2.6.10</akka.version>
        <scala.binary.version>2.13</scala.binary.version>
   </properties>

  <dependency>
       <groupId>com.typesafe.akka</groupId>
       <artifactId>akka-actor-typed_${scala.binary.version}</artifactId>
       <version>${akka.version}</version>
  </dependency>
<!-- akka-testkit是AKKA提供的测试工具包 -->
  <dependency>
      <groupId>com.typesafe.akka</groupId>
      <artifactId>akka-testkit_${scala.binary.version}</artifactId>
      <version>${akka.version}</version>
      <scope>test</scope>
  </dependency>

创建一个domain class

public class Request {
    private final String key;
    private final Object value;

    public Request(String key, Object value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public Object getValue() {
        return value;
    }
}

创建Actor类

import akka.actor.AbstractActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import lombok.ToString;


import java.util.HashMap;
import java.util.Map;
@ToString
public class RequestActor extends AbstractActor {
    protected final LoggingAdapter log = Logging.getLogger(context().system(),this);
    protected final Map<String,Object> map = new HashMap<>();

    @Override
    public Receive createReceive() {
        return receiveBuilder().
                match(Request.class,message ->{
                    log.info("Received Request {}",message);
                    map.put(message.getKey(), message.getValue());
                })
                .matchAny(o->log.info("Received unknow message {}",o))
                .build();
    }
}

创建测试类

class RequestActorTest {
    ActorSystem system = ActorSystem.create();
    @Test
    public void test() {
        TestActorRef<RequestActor> actorRef = TestActorRef.create(system, Props.create(RequestActor.class));
        actorRef.tell(new Request("key","value"), ActorRef.noSender());
        RequestActor requestActor = actorRef.underlyingActor();
        System.out.println(requestActor.toString());
        assertEquals(requestActor.map.get("key"),"value");
    }
}
posted @ 2020-11-01 23:32  听说这是最长的名字了  阅读(222)  评论(0编辑  收藏  举报