Play framework - How to set cache timeout in conf file

360 Views Asked by At

I'm working on an app using Play framework 2.6. (launched using sbt, if that matters) I would like to set cache timeouts to a certain limit using configuration, rather than individually for each endpoint.

The old version seems to have had something like this - https://www.playframework.com/documentation/1.2.3/configuration#http

But this doesn't work for my current project. Any pointers?

(Running the app in production mode on my local sets it to: Cache-Control: max-age=0)

1

There are 1 best solutions below

0
Daniel Hinojosa On BEST ANSWER

Try the following, create your own Adapter Pattern around the Cache API:

package caching

import javax.inject._
import play.api.Configuration
import play.api.cache.AsyncCacheApi

import scala.concurrent.duration.Duration

@Singleton
class ConfigCache @Inject()(config: Configuration, cache: AsyncCacheApi) {
  def set(name: String, obj: Any) = {
    cache.set(name, obj, config.get[Duration]("my.play.duration"))
  }
}

Now that you have a ConfigCache class you can inject that where needed...

package controllers

import javax.inject._
import play.api._
import play.api.mvc._
import services.Counter
import caching.ConfigCache
import models.Account

@Singleton
class SomeController @Inject() (configCache: ConfigCache, cc: ControllerComponents)(implicit executionContext: ExecutionContext) extends AbstractController(cc) {

  def myAction = Action {
    configCache.set("my.item", Account(1, "[email protected]", 
                    "Bob", "Bobberson", "pass"))
    Ok("Yay")
  }
}

Try it out. Not exact code. I just put some code together without checking. I would say don't use the word 'cache' as a package as I think that's a reserved package name. Let us know how it goes and what your final answer is. ;)