我是父母 - >将actor文件上传到Dropbox的子actor关系。该关系由主管演员和上传演员组成。主管人员为上传主体定义主管策略。因此,如果上传到Dropbox失败,只要达到最大重试次数,就应该重新启动actor。在我的申请中,我对上传的状态感兴趣。因此,我使用ask模式来获得成功或失败案例的未来。您可以在下面找到我演员的当前实现。
/**
* An upload message.
*
* @param byte The byte array representing the content of a file.
* @param path The path under which the file should be stored.
*/
case class UploadMsg(byte: Array[Byte], path: String)
/**
* The upload supervisor.
*/
class UploadSupervisor extends Actor {
/**
* Stores the sender to the executing actor.
*/
val senders: ParHashMap[String, ActorRef] = ParHashMap()
/**
* Defines the supervisor strategy
*/
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: DbxException => Restart
case e: Exception => Stop
}
/**
* Handles the received messages.
*/
override def receive: Actor.Receive = {
case msg: UploadMsg =>
implicit val timeout = Timeout(60.seconds)
val actor = context.actorOf(PropsContext.get(classOf[UploadActor]))
senders += actor.path.toString -> sender
context.watch(actor)
ask(actor, msg).mapTo[Unit] pipeTo sender
case Terminated(a) =>
context.unwatch(a)
senders.get(a.path.toString).map { sender =>
sender ! akka.actor.Status.Failure(new Exception("Actor terminated"))
senders - a.path.toString
}
}
}
/**
* An aktor which uploads a file to Dropbox.
*/
class UploadActor @Inject() (client: DropboxClient) extends Actor {
/**
* Sends the message again after restart.
*
* @param reason The reason why an restart occurred.
* @param message The message which causes the restart.
*/
override def preRestart(reason: Throwable, message: Option[Any]): Unit = {
super.preRestart(reason, message)
message foreach { self forward }
}
/**
* Handles the received messages.
*/
override def receive: Receive = {
case UploadMsg(byte, path) =>
val encrypted = encryptor.encrypt(byte)
val is = new ByteArrayInputStream(encrypted)
try {
client.storeFile("/" + path, DbxWriteMode.force(), encrypted.length, is)
sender ! (())
} finally {
is.close()
}
}
}
我现在的问题是:是否有更好的解决方案告诉我的应用程序上传演员在指定的号码或重试后失败。特别是为演员存储发送者的地图感觉有点尴尬。
答案 0 :(得分:1)
您应该使用CircuitBreaker
val breaker =
new CircuitBreaker(context.system.scheduler,
maxFailures = 5,
callTimeout = 10.seconds,
resetTimeout = 1.minute)
然后通过破坏者包装你的消息:
sender() ! breaker.withSyncCircuitBreaker(dangerousCall)
Breaker有三种状态:Closed,Open和HalfOpen。正常状态为“已关闭”,当消息失败时,$ maxFailures次数状态将更改为“打开”。 Breaker为状态更改提供回调。如果你想做某事使用它。例如:
breaker onOpen { sender ! FailureMessage()}