Play 2.4-Java-参与者消息协议最佳实践

Play 2.4-Java-参与者消息协议最佳实践,java,playframework,akka,Java,Playframework,Akka,我正在阅读关于Playframework中Akka actors实现的文档 其中一段讨论消息类最佳实践,如下所示: “此处显示的另一个最佳实践是,HelloActor发送和接收的消息被定义为另一个名为HelloActor协议的类的静态内部类:” 请有人详细说明和解释这种最佳做法,以及这种模式的好处是什么?为什么要将消息定义为其他类的静态嵌套类 提前谢谢你 我认为这背后的主要思想是隔离发送给特定参与者的消息的范围。输入协议有助于减少向参与者发送意外协议(或消息)。将它们保存在一个类中是捕获与特定

我正在阅读关于Playframework中Akka actors实现的文档

其中一段讨论消息类最佳实践,如下所示:

“此处显示的另一个最佳实践是,HelloActor发送和接收的消息被定义为另一个名为HelloActor协议的类的静态内部类:”

请有人详细说明和解释这种最佳做法,以及这种模式的好处是什么?为什么要将消息定义为其他类的静态嵌套类


提前谢谢你

我认为这背后的主要思想是隔离发送给特定参与者的消息的范围。输入协议有助于减少向参与者发送意外协议(或消息)。将它们保存在一个类中是捕获与特定域相关的所有操作的好方法,如
EmployeeProtocol
有助于强制执行
EmployeeActor
,以接收预期的消息。但是,您仍有责任正确发送:

下面是我们使用协议对EmployeeActor的控制器调用:

public class EmployeeController extends Controller {
    return Promise.wrap(ask(employeeActorRef, 
        new GetCurrentEmployees(), 5000))
            .map(response -> ok((JsonNode)response));
    }
}
public class EmployeeActor extends UntypedActor {

    @Override
    public void onReceive(Object message) throws Exception {
        if (message instanceof GetCurrentEmployees) {
            //do things related to this task
        } else if (message instanceof CreateNewEmployee) {
            //do things related to this task            
        } else if (message instanceof RemoveEmployee) {
            //do things related to this task            
        }
    }
}
EmployeeActor根据收到的协议处理其消息:

public class EmployeeController extends Controller {
    return Promise.wrap(ask(employeeActorRef, 
        new GetCurrentEmployees(), 5000))
            .map(response -> ok((JsonNode)response));
    }
}
public class EmployeeActor extends UntypedActor {

    @Override
    public void onReceive(Object message) throws Exception {
        if (message instanceof GetCurrentEmployees) {
            //do things related to this task
        } else if (message instanceof CreateNewEmployee) {
            //do things related to this task            
        } else if (message instanceof RemoveEmployee) {
            //do things related to this task            
        }
    }
}
在这里,协议是为员工的操作定义的,可以保存类型化字段,这样我们就知道需要什么了。我们在协议中使用静态final字段的事实将强制消息的不变性:

public class EmployeeProtocol {

    public static class GetCurrentEmployees {}
    public static class CreateNewEmployee {
        private final String name;
        public CreateNewEmployee(String name) {
            this.name = name;
        }
        //getter
    }
    public static class RemoveEmployee {
        public final String uuidToRemove;
        public RemoveEmployee(String uuidToRemove) {
            this.uuidToRemove = uuidToRemove;
        }
        //getter
    }
}
Akka Typed是在Akka scala中开发的,它只能用于发送特定类型的消息,因此,如果您试图发送错误的消息类型,编译器会抱怨。阿克卡打字-

也许他们希望我们使用这个最佳实践,因为我们将来可以使它的类型安全。。。在本播客中还提到了这一点: