码迷,mamicode.com
首页 > 其他好文 > 详细

AKKA | Hello AKKA

时间:2020-11-02 10:45:33      阅读:32      评论:0      收藏:0      [点我收藏+]

标签:sse   class   over   key   equal   prot   binary   safe   protected   

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");
    }
}

AKKA | Hello AKKA

标签:sse   class   over   key   equal   prot   binary   safe   protected   

原文地址:https://www.cnblogs.com/jj81/p/13912375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!