gpt4 book ai didi

java - Akka for Java,如何使用具有泛型的 Actor

转载 作者:搜寻专家 更新时间:2023-10-31 20:33:56 25 4
gpt4 key购买 nike

Akka似乎是一个很好的框架/概念,用于在您的应用程序中处理异步流。我目前正在为我的一个项目学习 Akka,我想知道如何正确设计 Actors。

想象一下下面的 Actor :

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 documentation 中描述.

上面的模式对我来说似乎有点老派,它有一堆instanceof检查并且actor处理Object。是否有另一种首选方法(例如您在其中指定您感兴趣的类型的某些基类)或类似方法。

我能看到的另一种选择是,例如,您继承了一个通用 Actor ,例如:

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

那么,与 Actor 合作的最佳实践是什么?它是在扩展 UntypedActor 还是我遗漏了什么?

最佳答案

首先看UntypedActoronReceive方法契约,专为 Scala 模式匹配而设计,简化的设计有一些美感。

使用 Java,您需要进行某种权衡。您可以使用 Visitor 的自定义实现每个 Actor 的模式,但它增加了不必要的努力。

最好是使用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);
}
}

关于java - Akka for Java,如何使用具有泛型的 Actor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28026804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com