• Classic Actor | Props


    Props是用于指定创建一个actor的选项的配置类,它是一个final class,因此可以把它视为不可变,可以共享用于创建actor的信息(例如指定哪个dispatcher)

    import akka.actor.Props;
    Props props1 = Props.create(MyActor.class);
    // 展示了如何将构造函数参数传递给正在创建的参与者,但是它只能在参与者之外使用。但这个不推荐使用,因为会破坏actor的封装性
    Props props2 = Props.create(ActorWithArgs.class, () -> new ActorWithArgs("arg"));  
    //展示传入构造参数的情况
    //会验证参数,如果没有找到或找到多个匹配构造函数,则会出现IllegalArgumentException异常。
    Props props3 = Props.create(ActorWithArgs.class, "arg");
    

    优雅创建Actor实践

    import akka.actor.AbstractActor;import akka.actor.Props;
    import akka.event.Logging;
    import akka.event.LoggingAdapter;
    import java.util.HashMap;
    import java.util.Map;
    public class RequestActor4 extends AbstractActor {
        protected final String name;
        protected final LoggingAdapter log = Logging.getLogger(context().system(),this);
        protected final Map<String, Object> map = new HashMap<>();
        public RequestActor4(String name) {
            this.name = name;
        }
        //将Props封装到Actor中,通过RequestActor4.Props(actorName)调用
        static Props props(String name) {
            return Props.create(RequestActor4.class, name);
        }
        @Override
        public Receive createReceive() {
            return receiveBuilder()
                    .match(String.class,message->{
                        log.info("Received Request {}",message);
                        map.put("StringMessage",message);
                    })
                    .matchAny(o->log.info("Received unknow message {}",o))
                    .build();
        }
    }
    
    
    import akka.actor.ActorRef;
    import akka.actor.ActorSystem;
    import akka.testkit.TestActorRef;
    import org.junit.jupiter.api.Test;
    import static org.junit.jupiter.api.Assertions.assertEquals;
    class RequestActorTest {
        ActorSystem system = ActorSystem.create();
        @Test
        public void test() {
          //采用工厂模式,传入Actor name 参数生成actor
            TestActorRef<RequestActor4> actorRef = TestActorRef.create(system, RequestActor4.props("request"));
            actorRef.tell(String.valueOf("this is a message"), ActorRef.noSender());
            RequestActor4 requestActor = actorRef.underlyingActor();
            assertEquals("request",requestActor.name);
            assertEquals("this is a message",requestActor.map.get("StringMessage"));
        }
    }
    
    
  • 相关阅读:
    家庭记账本开发记录2
    家庭记账本开发记录1
    构建之法阅读笔记——具体职位、用户和行业篇
    构建之法阅读笔记——团队篇
    js学习17
    js学习15
    js学习14
    js学习13
    js学习12
    js学习11
  • 原文地址:https://www.cnblogs.com/jj81/p/13966201.html
Copyright © 2020-2023  润新知