我们说我们有一个命令AddUser
:
case class AddUser(username: String, password: String)
在持久保存事件之前验证此命令的最佳方法是什么? 例如,以这样的方式做这件事似乎有点混乱。
override def receiveCommand: Receive = {
case AddUser(username, password) =>
if (username.trim.length > 25) {
sender() ! UsernameTooLong
} else if (password.trim.length > 25) {
sender() ! PasswordTooLong
} else {
persist(UserAdded(User(username, password))) {
userAdded =>
sender() ! userAdded
}
}
}
答案 0 :(得分:2)
您需要使用接收管道模式:http://doc.akka.io/docs/akka/2.4.1/contrib/receive-pipeline.html
你可以这样做:
trait AuthenticatedUser { this: ReceivePipeline =>
pipelineInner {
case msg@AddUser(username, password) =>
if (username.trim.length > 25) {
sender() ! UsernameTooLong
} else if (password.trim.length > 25) {
sender() ! PasswordTooLong
} else {
Inner(msg)
}
case msg => Inner(msg)
}
}
class UserActor extends Actor with ReceivePipeline with AuthenticatedUser {
def receive = {
case AddUser(username, password) =>
persist(UserAdded(User(username, password))) {
userAdded =>
sender() ! userAdded
}
}
}
PS:我没有编译和测试过这段代码,但我相信它会起作用,如果有任何问题请告诉我。