簡體   English   中英

Akka for Java,如何使用帶有泛型的Actor

[英]Akka for Java, how to use an an Actor with generics

在您的應用程序中使用異步流程時, Akka似乎是一個很好的框架/概念。 我正在為我的一個項目學習Akka,我想知道如何正確設計Actors。

想象一下下面的演員:

public class SampleActor extends UntypedActor {
    private final LoggingAdapter log = 
            Logging.getLogger(getContext().system(), this);

    @Override
    public void onReceive(final Object message) throws Exception {
        if (message instanceof SomeType) {
            SomeType someType = ((SomeType) message);
            // Handle SomeType
        } else if (message instance SomeOtherType) {
            SomeOtherType someOtherType = ((SomeOtherType) message);
            // Handle SomeOtherType
        } else {
            unhandled(message);
        }
    }
}

上面的代碼是一種常見的模式,例如在Akka文檔中描述的。

上面的模式對我來說似乎是一種老式的學校 ,有一堆instanceof檢查,並且actor處理Object 是否有另一種首選方法(如某些基類,您可以指定您感興趣的類型)或類似方法。

我可以看到的一個替代方案是你繼承一個通用的演員,例如:

public class SampleActor extends GenericActor<SomeType> {
    public void onReceive(final SomeType someType) throws Exception {
        // Do stuff
    }
}

那么,與演員合作的最佳做​​法是什么。 是擴展UntypedActor還是我遺漏了什么?

首先看看為Scala模式匹配設計的UntypedActoronReceive方法契約,並且在簡化設計中有一些美感。

使用Java,您需要某種權衡。 您可以為每個actor使用Visitor模式的自定義實現,但這會增加不必要的工作量。

最好的方法是使用AbstractActor及其PartialFunction<Object, BoxedUnit> receive()方法,由您自己的抽象支持。

public abstract class AbstractAggregateRegistryActor extends AbstractActor {

    @Override
    public PartialFunction<Object, BoxedUnit> receive() {
        return ReceiveBuilder.
                match(Protocol.AbstractComponentRegister.class, 
                                      this::handleRegistration).
                match(Protocol.AbstractComponentDeregister.class,
                                      this::handleDeregistration).
                match(Protocol.AbstractComponentRegistryRequest.class,
                                      this::handleRegistryRequest).
                matchAny(this::unhandled).build();
    }


    private void handleRegistration(Protocol.AbstractComponentRegister
                                    componentRegister) {
        .....
    }

    private void handleDeregistration(Protocol.AbstractComponentDeregister
                                      componentDeregister) {
        ...
    }

    protected abstract <T extends Protocol.AbstractComponentRegistryRequest> 
                         void handleRegistryRequest(T registryRequest);


    @Override
    public void unhandled(Object message) {
        log.warning("Unhandled message {} in registry.", message);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM