Book Image

Getting Started with Memcached

By : Ahmed Soliman
Book Image

Getting Started with Memcached

By: Ahmed Soliman

Overview of this book

<p>Web application performance is no longer a non-functional requirement, but an implicit condition for an engaging user experience. As a result, responsive and highly scalable applications are becoming a necessity. Memcached is a high-performance distributed memory caching system built to speed up dynamic web applications by offloading pressure from your database. <br /><br />Getting Started with Memcached is a hands-on, comprehensive guide to the Memcached service and it’s API in different programming languages. It contains practical recipes to integrate Memcached within your Rails, Django, or even Scala Play! applications.<br /><br />This book will show you everything you need to know to start using Memcached in your existing or new web applications.<br />This book uses real-world recipes to help you learn how to store and retrieve data from your clustered virtual memory cache pool and how to integrate caching into your favourite web development framework.</p> <p><br />You will also learn how to build a Memcached consistent-hashing scalable cluster and how Memcached clients are properly configured to use different servers to scale out your memory cache pool in Ruby, Python, PHP, and Java. With this book, you will see how to cache templates and database queries in the most popular web development framework in use today.</p>
Table of Contents (9 chapters)

Setting up memcached to support in Play (Intermediate)


Play Framework is a modern Java/Scala framework that promises a lightweight, stateless, Web-friendly architecture.

It's built on Akka and it's very reliable for building highly-scalable applications with predictable resource consumption.

Play 2 is the next generation of the framework; it has gone through almost a complete rewrite, and it's now fully written in Scala but offers a good Java API. We will be focusing on Scala examples right here.

Play 2 uses Ehcache by default as a backend, you can always replace the backend by writing plugins for Play 2, fortunately, someone already did that and it's using the spymemcached java client for memcached.

We are using Play 2.2.X for this recipe which uses sbt 0.13.X.

Getting ready

  1. Let's start by creating a simple play project.

    play new playcache
  2. Select create a simple Scala application.

  3. Then we need to configure our project's build.sbt to use play2-memcached as a dependency. Edit your build.sbt to look like the following:

    name := "playcache"
    
    version := "1.0-SNAPSHOT"
    libraryDependencies ++= Seq(
      jdbc,
      anorm,
      cache,
      "com.github.mumoshu" %% "play2-memcached" % "0.3.0.2"
    )     
    
    resolvers += "Spy Repository" at "http://files.couchbase.com/maven2"
    
    play.Project.playScalaSettings

How to do it...

  1. We need to configure our play application to use memcached instead of the default Ehcache backend for the Caching API of Play Start by adding the play2-memcached plugin to conf/play.plugins (create the file if not created already)

    5000:com.github.mumoshu.play2.memcached.MemcachedPlugin
  2. Then, let's edit the configuration conf/application.conf file and add near the end of the file, the following line to disable the ehcache plugin:

    ehcacheplugin=disabled
  3. Now, let's configure the memcached plugin to the memcached server:

    memcached.host="127.0.0.1:11211"
  4. After that, you are ready to use memcached, start the application server by running:

    play run
  5. Then, let's edit the controller at app/controllers/Application.scala to look like the following snippet:

    package controllers
    
    import play.api._
    import play.api.mvc._
    import play.api.cache.Cache
    import play.api.Play.current
    
    object Application extends Controller {
      def index = Action {
        Cache.getAs[String]("key") match {
          case Some(v) =>
            Ok(s"Got the value from cache: $v")
          case None =>
            Cache.set("key", "Fantastic Value", 50)
              Ok("Setting value in Cache")
        }    
      }
    
    }
  6. From your browser, visithttp://localhost:9000/ and see what happens. On your first request you should see something like the following:

    Setting value in Cache
  7. Then if you refreshed the page, you will see the following line:

    Got the value from cache: Fantastic Value
  8. One more thing you can do is to cache the entire action response by using the Cached object for that.

    def index = Cached("homePage") {
      Action {
        Ok("Hello world")
      }
    }

Congratulations, Play 2 is now connected and uses memcached as the caching backend.

How it works...

First, we needed to edit the build script (build.sbt) to add the play2-memcached as a dependency, we did that by appending in the libraryDependencies setting key the value to "com.github.mumoshu" %% "play2-memcached" % "0.3.0.2".

Then, we added a resolver to tell sbt where to get this plugin from. Next, we created/edited the conf/play.plugins file to add the plugin to play and we configured conf/application.conf to point to our memcached server.

In the controller code, we used the play.api.cache.Cache object to get and set values from the cache.

The last thing is that you can use the Cached object to cache the entire action response in a named cache key "homePage".

There's more...

If you are planning to use Play2 with a memcached cluster, you will need to configure the list of your servers in conf/application.conf.

The configuration is really straightforward. Just replace memcached.host="127.0.0.1:11211"with the list of the servers as follows:

memcached.1.host="cache-1.example.com:11211"
memcached.2.host="cache-1.example.com:11211"

As mentioned several times before, it's important to keep this list in-sync for all your Play servers.