Book Image

Play Framework Essentials

By : Julien Richard-Foy
Book Image

Play Framework Essentials

By: Julien Richard-Foy

Overview of this book

Table of Contents (14 chapters)
Play Framework Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Saving computation time using cache


Using a cache can help you to avoid computing things several times. Web applications support two kinds of caches: server-side and client-side caches. The latter can save HTTP round trips. In both cases, dealing with expiration can be a complex task!

Play provides a minimal cache library and some controller level caching features that can help you leverage both client-side and server-side caches. The implementation uses EhCache under the hood and, by default, caches things in memory only. You'll find more about EhCache at http://ehcache.org/.

To use it, you first need to add it to your build dependencies:

libraryDependencies += cache

The cache basically works as a key-value store. You can store values for a given duration and retrieve them using a key. Let's use it in the Application.index action that just displays a static HTML page:

import play.api.cache.Cache
val index = Action {
  Ok(Cache.getOrElse("main-html")(views.html.main()))
}

The getOrElse method...