[英]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模式匹配设计的UntypedActor
和onReceive
方法契约,并且在简化设计中有一些美感。
使用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.