Skip to content

Instantly share code, notes, and snippets.

@takashima0411
Last active May 31, 2018 21:05
Show Gist options
  • Save takashima0411/f2e4f0062f7d7d585e034479b467069c to your computer and use it in GitHub Desktop.
Save takashima0411/f2e4f0062f7d7d585e034479b467069c to your computer and use it in GitHub Desktop.
private val bucket = new NanoTimeTokenBucket(1, 1250.milliseconds.toNanos)
def of = synchronized(bucket.offer(1).nanos.toMillis)
def req[T](uri: Uri, opWhenSuccess: HttpResponse => Source[T, NotUsed]): Future[Source[T, NotUsed]] = Future {
RestartSource.withBackoff(200.millis, 30.seconds, 2.0, 3) { () =>
Source.fromFutureSource {
Thread.sleep(of)
Http().singleRequest(HttpRequest(uri = uri)).map { res =>
if (res.status.intValue() == 200) {
res.headers.find(_.is("retry-after")).foreach(h => logger.debug(h.toString()))
res.headers.find(_.is("x-app-rate-limit-count")).foreach(h => logger.debug(h.toString()))
opWhenSuccess(res)
} else {
logger.debug(res.toString())
Source.empty
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment