Skip to content

Instantly share code, notes, and snippets.

@adamw
Last active June 6, 2018 10:55
Show Gist options
  • Select an option

  • Save adamw/399082948502c55694eb861428ec809d to your computer and use it in GitHub Desktop.

Select an option

Save adamw/399082948502c55694eb861428ec809d to your computer and use it in GitHub Desktop.
class AkkaTypedRateLimiter(actorSystem: ActorSystem[RateLimiterMsg])
extends StrictLogging {
def runLimited[T](f: => Future[T])(implicit ec: ExecutionContext): Future[T] = {
val p = Promise[T]
actorSystem ! LazyFuture(() => f.andThen { case r => p.complete(r) }.map(_ => ()))
p.future
}
}
object AkkaTypedRateLimiter {
def create(maxRuns: Int, per: FiniteDuration): AkkaTypedRateLimiter = {
val behavior = Behaviors.withTimers[RateLimiterMsg] { timer =>
rateLimit(timer, RateLimiterQueue(maxRuns, per.toMillis))
}
new AkkaTypedRateLimiter(ActorSystem(behavior, "rate-limiter"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment