Cache solution to manage external api calls using play framework

153 Views Asked by At

I have some external paid api that I use to retrieve data based on some id, and some of the calls I will perform will probably have the same id, so im looking for the best practice in play to manage this kind of scenario with cache. also I want to be able to delete the cache after 24 hrs.

any recommendations ?

thanks!

1

There are 1 best solutions below

0
C4stor On BEST ANSWER

Play documentation gives (imo) clear indications about what to do : https://www.playframework.com/documentation/2.6.x/ScalaCache

The gist of it is :

  • Inject a cache instance where needed :
  • Use your instance to cache stuff :

So basiscally :

import play.api.cache._
import play.api.mvc._
import javax.inject.Inject

class Application @Inject() (cache: AsyncCacheApi, cc:ControllerComponents) extends AbstractController(cc) {

[...]
val result: Future[Done] = cache.set("item.key", connectedUser, 24.hours)
val futureMaybeUser: Future[Option[User]] = cache.get[User]("item.key")
}