Reputation: 111
I am trying figure out the best way to retrieve the contents from a GET http request with using a timeout. I spent a good amount of time trying to figure out the best approach, but I am a little unsure.
Basically I just want to have an option that will return None if the response does not come before the timeout, otherwise return the contents.
Thanks
Upvotes: 2
Views: 90
Reputation: 2804
So I suppose you are trying to solve 2 problems. How to define a particular timeout in the configuration and then how to manage timeouts when they happen.
Define http client timeouts: You will need to update your application.conf
to overwrite the default configuration of the http client. e.g.:
spray.can {
client {
request-timeout = 20s
}
}
Managing timeouts: When you use the spray client, you will use a pipeline
that will run the requests. It will be a function that looks something like (HttpRequest) => Future[ObjectResponse]
.
The result will be a Future
of an object you have defined ,ObjectResponse
in my example, you can resolve the future. In case a there is a timeout, the Future
will become a RequestTimeoutException. Then you will be able to process the timeout exception with a recover
. So your code will look something like this:
def sendRequestFunction(...): Future[ObjectResponse] = {...}
sendRequestFunction(parameters) map (Option) // In case we get an object, we will have a Some(obj)
recover {
case e: RequestTimeoutException => None
}
Upvotes: 1
Reputation: 19
You can try something like this:
timedOutFuture = after(duration = duration, using = system.scheduler) {
Future.successfull(None)
}
Future.firstCompletedOf(Seq(youHttpRequestFuture, timedOutFuture))
Hope it helps
Upvotes: 0