Book Image

Play Framework Cookbook

By : Alexander Reelsen
Book Image

Play Framework Cookbook

By: Alexander Reelsen

Overview of this book

<p>The Play framework is the new kid on the block of Java frameworks. By breaking with existing standards the play framework tries not to abstract away from HTTP as most web frameworks do, but tightly integrates with it. This means quite a shift for Java programmers. Understanding these concepts behind the play framework and its impact on web development with Java are crucial for fast development of applications.<br /><br />The Play Framework Cookbook starts where the beginner documentation ends. It shows you how to utilize advanced features of the Play framework &ndash; piece by piece and completely outlined with working applications!<br /><br />The reader will be taken through all layers of the Play Framework and provided with in-depth knowledge from as many examples and applications as possible. Leveraging the most from the Play framework means to think simple again in a java environment. Implement your own renderers, integrate tightly with HTTP, use existing code, improve site performance with caching and integrate with other web services and interfaces. Learn about non-functional issues like modularity or integration into production and testing environments. In order to provide the best learning experience during reading Play Framework Cookbook, almost every example is provided with source code, so you can start immediately to integrate recipes into your own play applications.</p>
Table of Contents (16 chapters)
Play Framework Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Further Information About the Play Framework
Index

Understanding session management


Whenever you read about Play, one of the first advantages you will hear is that it is stateless. But what does this mean actually? Does it mean you do not have a session object, which can be used to store data while a visitor is on your website? No, but you have to rethink the way sessions are used.

Usually a session in a servlet-based web application is stored on a server side. This means, every new web request is either matched to a session or a new one is created. This used to happen in memory, but can also be configured to be written on disk in order to be able to restart the servlet container without losing session data. In any scenario there will be resources used on the server side to store data which belongs to a client.

Imagine a server environment with two servers receiving all HTTP connections. After the session has been created on server A, some logic has to redirect the user with this session always to server A, because otherwise a new session would have to be created on server B without taking over the session data from server A. Alternatively, the sessions have to be shared somehow. Both solutions require additional logic somewhere.

Play goes the way of sharing the session, but in a slightly different way. First, the real session used to identify the client is stored as a Cookie on the client. This cookie is encrypted and cannot be tampered with. You can store data in this cookie; however, the maximum cookie size is only 4KB. Imagine you want to store big data in this session, like a very large shopping cart or a rendered graphic. This would not work.

Play has another mechanism to store big data, basically a dumb cache. Caches are good at storing temporary data as efficient and fast accessible as possible. Furthermore, this allows you to have a scaling caching server, as your application scales. The maximum session size is 4KB. If you need to store more data, just use a cache.

How to do it...

Use the session object inside the controller to write something into it. This is a standard task during a login:

public static void login(String login, String password) {
    User user = User.find("byLoginAndPassword", login, password).first();
    notFoundIfNull(user);
    session.put("login", user.login);
    index();
}

The session variable can now be accessed from any other controller method as long as it is not deleted. This works for small content, like a login:

String login = session.get("login");

Now, you can also use the built-in cache functionality instead of the session to store data on the server side. The cache allows you to put more data than the session maximum of 4 kilobytes into the cache (for the sake of having a lot of data assume that you are a subcontractor of Santa Claus, responsible for the EMEA region and constantly filling your shopping cart without checking out):

Cache.set(login, shoppingCart, "20mn");

Querying is as easy as calling:

Cache.get(login)

How it works...

Adding data to the session is as easy as using a regular session object. However, there is no warning if there is data put into the session, which is bigger than the maximum allowed cookie size. Unfortunately, the application will just break when getting the data out of the cookie, as it is not stored in the cookie, and the session.get() call will always fail.

In order to avoid this problem, just use the Cache class for storing such data. You can also add a date when the data should expire out of the cache.

There's more...

Caching is a very powerful weapon in the fight for performance. However, you always gain performance at the cost of reducing the actuality of your data. Always decide what is more important. If you can keep your data up-to-date by scaling out and adding more machines, this might be more useful in some cases, than caching it. As easy as caching is, it should always be the last resort.

Configuring different cache types

If you have a setup with several Play nodes, there is a problem if every instance uses its own cache, as this can lead to data inconsistency among the nodes. Therefore, Play comes with support to offload cache data to memcached instead of using the built-in Java-based EhCache. You will not have to change any of your application code to change to memcached. The only thing to change is the configuration file:

memcached=enabled
memcached.host=127.0.0.1:11211

Using the cache to offload database load

You can store arbitrary data in your cache (as long as it is serializable). This offers you the possibility to store queries to your persistence engine in the cache. If 80 percent of your website visits only hit the first page of your application, where the 10 most recent articles are listed, it makes absolute sense to cache them for a minute or 30 seconds. However, you should check whether it is really necessary as many databases are optimizing for this case already; please check your implementation for that.

See also

There is a recipe on writing your own cache implementation in Chapter 4 called Writing your own cache implementation, where Hazelcast is used to store data. In Chapter 3 there is also a general recipe Basics of caching about caching different aspects of your application.