我正在制作一个用于组合重试执行策略的 Monoid,而 RetryExecutor[T] 是基于类型的。我已经定义了以下基本类型和一个幺半群:
trait RetryExecutor[C] {
def retry[T](f: C => T)(context: C): T
def predicate: Option[Throwable]
def application: Unit
val retryEligible: PartialFunction[Throwable, Boolean]
}
object RetryExecutor {
implicit def retryExecutorMonoid[A] = new Monoid[RetryExecutor[A]] {
...
}
和一些基本类型,如:
case class LinearDelayingRetryExecutor[C](delayInMillis: Long)(val retryEligible: PartialFunction[Throwable, Boolean]) extends RetryExecutor[C] {
override def predicate: Option[Throwable] = None
override def application = Thread.sleep(delayInMillis)
}
case class RetryWithCountExecutor[C](maximumRetries: Int)(val retryEligible: PartialFunction[Throwable, Boolean])(implicit val logger: Logger) extends RetryExecutor[C] {
var remainingTries = maximumRetries + 1
override def application: Unit = {
remainingTries = remainingTries - 1
}
override def predicate: Option[Throwable] = {
if (remainingTries > 0) None
else Some(RetryingException("Retry count of " + maximumRetries + " exceeded for operation"))
}
}
我可以手动组合它们:
val valid: PartialFunction[Throwable, Boolean] = { case x: TestException => true }
val monoid = RetryExecutor.retryExecutorMonoid[Int]
val x = monoid.append(RetryWithCountExecutor[Int](3)(valid), LinearDelayingRetryExecutor(100)(valid))
但是当我尝试使用附加运算符时:
val x = RetryWithCountExecutor[Int](3)(valid) |+| LinearDelayingRetryExecutor(100)(valid)
我得到一个编译错误:
[error] /Users/1000306652a/work/src/test/scala/com/foo/bar/RetryExecutorSpec.scala:25: value |+| is not a member of com.foo.bar.retry.RetryWithCountExecutor[Int]
[error] val k: RetryExecutor[Int] = RetryWithCountExecutor[Int](3)(valid) |+| BackingOffRetryExecutor[Int](100)(valid)