Caching HTTP session data

duration 25 minutes

Prerequisites:

Learn how to create, use, and cache HTTP session data for your application.

What you’ll learn

What is a session?

On the internet, a web server doesn’t know who you are or what you do because it’s processing stateless HTTP requests. An HTTP session provides a way to store information to be used across multiple requests. Session variables store user information like user name or items in a shopping cart. By default, session variables will timeout after 30 minutes of being unused. Cookies, which also store user information, are maintained on a client’s computer, whereas session variables are maintained on a web server. For security reasons, an HTTP session is preferred over cookies when used with sensitive data. A session hides data from users. Cookies can be manipulated by a savvy user to make fake requests to your site.

What is session persistence?

High traffic websites must support thousands of users in a fast and reliable way. Load balancing requires running several instances of the same application in parallel so that traffic can be routed to different instances to maximize speed and reliability. Unless a user is tied to a particular instance, running multiple instances of the same application can pose an out-of-sync problem when each instance keeps an isolated copy of its session data. HTTP session data caching can solve this problem by allowing all instances of the application to share caches among each other. Sharing caches among instances eliminates the need to route a user to the same instance and helps in failover situations by distributing the cache.

Session Cache

You will learn how to build an application that creates and uses HTTP session data. You will also learn how to use Open Liberty’s sessionCache feature to persist HTTP sessions by using Java Caching (JCache), the standard caching API for Java.

You will containerize and deploy the application to a local Kubernetes cluster. You will then replicate the application in multiple pods and see that the session data is cached and shared among all instances of the application. Even if an instance is unavailable, the other instances are able to take over and handle requests from the same user by using the cached session data.

Additional prerequisites

Before you begin, you need a containerization software for building containers. Kubernetes supports various container runtimes. You will use Docker in this guide. For Docker installation instructions, refer to the official Docker documentation.

Use Docker Desktop, where a local Kubernetes environment is pre-installed and enabled. If you do not see the Kubernetes tab, then upgrade to the latest version of Docker Desktop.

Complete the setup for your operating system:

After you complete the Docker setup instructions for your operating system, ensure that Kubernetes (not Swarm) is selected as the orchestrator in Docker Preferences.

Use Docker Desktop, where a local Kubernetes environment is pre-installed and enabled. If you do not see the Kubernetes tab, then upgrade to the latest version of Docker Desktop.

Complete the setup for your operating system:

After you complete the Docker setup instructions for your operating system, ensure that Kubernetes (not Swarm) is selected as the orchestrator in Docker Preferences.

You will use Minikube as a single-node Kubernetes cluster that runs locally in a virtual machine. For Minikube installation instructions, see the Minikube documentation. Be sure to read the Requirements section, as different operating systems require different prerequisites to run Minikube.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-sessions.git
cd guide-sessions

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Creating the application

The application that you are working with is a shopping cart web service that uses JAX-RS, which is a Java API for building RESTful web services. You’ll learn how to persist a user’s shopping cart data between servers by using the sessionCache feature in Open Liberty. The sessionCache feature persists HTTP sessions using JCache. You can have high-performance HTTP session persistence without using a relational database.

Navigate to the start directory to begin.

Create the CartApplication class.
src/main/java/io/openliberty/guides/cart/CartApplication.java

CartApplication.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2019 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.cart;
14
15import javax.ws.rs.ApplicationPath;
16import javax.ws.rs.core.Application;
17
18@ApplicationPath("/")
19public class CartApplication extends Application {
20
21}

The CartApplication class extends the generic JAX-RS application class that is needed to run the application.

Create the CartResource class.
src/main/java/io/openliberty/guides/cart/CartResource.java

CartResource.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2019 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13package io.openliberty.guides.cart;
 14
 15import java.util.ArrayList;
 16import java.util.Enumeration;
 17import java.util.Properties;
 18
 19import javax.json.Json;
 20import javax.json.JsonArrayBuilder;
 21import javax.json.JsonObject;
 22import javax.json.JsonObjectBuilder;
 23import javax.servlet.http.HttpServletRequest;
 24import javax.servlet.http.HttpSession;
 25import javax.ws.rs.GET;
 26import javax.ws.rs.POST;
 27import javax.ws.rs.Path;
 28import javax.ws.rs.PathParam;
 29import javax.ws.rs.Produces;
 30import javax.ws.rs.core.Context;
 31import javax.ws.rs.core.MediaType;
 32import javax.ws.rs.core.Response;
 33
 34import org.eclipse.microprofile.openapi.annotations.Operation;
 35import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
 36import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
 37
 38@Path("/")
 39public class CartResource {
 40
 41    @POST
 42    // tag::endpointCartItemPrice[]
 43    @Path("cart/{item}&{price}")
 44    // end::endpointCartItemPrice[]
 45    @Produces(MediaType.TEXT_PLAIN)
 46    @APIResponse(responseCode = "200", description = "Item successfully added to cart.")
 47    @Operation(summary = "Add a new item to cart.")
 48    // tag::addToCart[]
 49    public String addToCart(@Context HttpServletRequest request,
 50                    @Parameter(description = "Item you need for intergalatic travel.",
 51                               required = true)
 52                    // tag::item[]
 53                    @PathParam("item") String item,
 54                    // end::item[]
 55                    @Parameter(description = "Price for this item.",
 56                               required = true)
 57                    // tag::price[]
 58                    @PathParam("price") double price) {
 59                    // end::price[]
 60        // tag::getSession[]
 61        HttpSession session = request.getSession();
 62        // end::getSession[]
 63        // tag::setAttribute[]
 64        session.setAttribute(item, price);
 65        // end::setAttribute[]
 66        return item + " added to your cart and costs $" + price;
 67    }
 68    // end::addToCart[]
 69
 70    @GET
 71    // tag::endpointCart[]
 72    @Path("cart")
 73    // end::endpointCart[]
 74    @Produces(MediaType.APPLICATION_JSON)
 75    @APIResponse(responseCode = "200",
 76        description = "Items successfully retrieved from your cart.")
 77    @Operation(summary = "Return an JsonObject instance which contains " +
 78                         "the items in your cart and the subtotal.")
 79    // tag::getCart[]
 80    public JsonObject getCart(@Context HttpServletRequest request) {
 81        HttpSession session = request.getSession();
 82        Enumeration<String> names = session.getAttributeNames();
 83        JsonObjectBuilder builder = Json.createObjectBuilder();
 84        // tag::podname[]
 85        builder.add("pod-name", getHostname());
 86        // end::podname[]
 87        // tag::sessionid[]
 88        builder.add("session-id", session.getId());
 89        // end::sessionid[]
 90        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
 91        Double subtotal = 0.0;
 92        while (names.hasMoreElements()) {
 93            String name = names.nextElement();
 94            String price = session.getAttribute(name).toString();
 95            arrayBuilder.add(name + " | $" + price);
 96            subtotal += Double.valueOf(price).doubleValue();
 97        }
 98        // tag::cart[]
 99        builder.add("cart", arrayBuilder);
100        // end::cart[]
101        builder.add("subtotal", subtotal);
102        return builder.build();
103    }
104    // end::getCart[]
105
106    private String getHostname() {
107        String hostname = System.getenv("HOSTNAME");
108        if (hostname == null)
109                hostname = "localhost";
110                return hostname;
111    }
112}

The CartResource class defines the REST endpoints at which a user can make an HTTP request.

The addToCart and getCart methods have a number of annotations. Most of these annotations are used by the MicroProfile OpenAPI and JAX-RS features to document the REST endpoints and map Java objects to web resources. More information about these annotations can be found in the Documenting RESTful APIs and Creating a RESTful web service guides.

The cart/{item}&{price} endpoint demonstrates how to set session data. The @PathParam annotation injects a custom item and price from the POST request into the method parameter. The addToCart method gets the current session and binds the {item}:{price} key-value pair into the session by the setAttribute() method. A response is then built and returned to confirm that an item was added to your cart and session.

The cart endpoint demonstrates how to get session data. The getCart method gets the current session, iterates through all key-value pairs that are stored in the current session, and creates a JsonObject response. The JsonObject response is returned to confirm the server instance by pod-name, the session by session-id, and the items in your cart by cart.

Configuring session persistence

Using client-server vs peer-to-peer model

Session caching is only valuable when a server is connected to at least one other member. There are two different ways session caching can behave in a cluster environment:

  • Client-server model: A Liberty server can act as the JCache client and connect to a dedicated JCache server.

  • Peer-to-peer model: A Liberty server can connect with other Liberty servers that are also running with the session cache and configured to be part of the same cluster.

You’ll use the peer-to-peer model in a Kubernetes environment for this guide.

Configuring session persistence with JCache in Open Liberty

JCache, which stands for Java Caching, is an interface to standardize distributed caching on the Java platform. The sessionCache feature uses JCache, which allows for session persistence by providing a common cache of session data between servers. This feature doesn’t include a JCache implementation. For this guide, you’ll use Hazelcast as an open source JCache provider.

Hazelcast is a JCache provider. Open Liberty needs to be configured to use Hazelcast after the sessionCache feature is enabled.

Create the server.xml file.
src/main/liberty/config/server.xml

server.xml

 1<!-- tag::copyright[] -->
 2<!--
 3     Copyright (c) 2019 IBM Corporation and others.
 4     All rights reserved. This program and the accompanying materials
 5     are made available under the terms of the Eclipse Public License
 6     v1.0 which accompanies this distribution, and is available at
 7     http://www.eclipse.org/legal/epl-v10.html
 8
 9     Contributors:
10         IBM Corporation - Initial implementation
11-->
12<!-- end::copyright[] -->
13<server description="Liberty Server for Sessions Management">
14
15    <featureManager>
16        <feature>servlet-4.0</feature>
17        <!-- tag::sessionCache[] -->
18        <feature>sessionCache-1.0</feature>
19        <!-- end::sessionCache[] -->
20        <feature>jaxrs-2.1</feature>
21        <feature>jsonp-1.1</feature>
22        <feature>mpOpenAPI-1.1</feature>
23    </featureManager>
24
25    <httpEndpoint httpPort="${default.http.port}" httpsPort="${default.https.port}"
26        id="defaultHttpEndpoint" host="*" />
27    <!-- tag::httpSessionCache[] -->
28    <httpSessionCache libraryRef="jCacheVendorLib"
29        uri="file:${shared.config.dir}/hazelcast-config.xml" />
30    <!-- end::httpSessionCache[] -->
31    <!-- tag::library[] -->
32    <library id="jCacheVendorLib">
33              <!-- tag::hazelcastjar[] -->
34        <file name="${shared.resource.dir}/hazelcast.jar" />
35        <!-- end::hazelcastjar[] -->
36    </library>
37    <!-- end::library[] -->
38
39    <webApplication location="cart-app.war" contextRoot="${app.context.root}" />
40
41</server>

The <library /> tag includes the library reference that indicates to the server where the Hazelcast implementation of JCache is located. The hazelcast.jar file is downloaded as a dependency and copied to the predefined {shared.resource.dir} directory when the Maven build runs. This goal is defined in the provided Maven POM file.

Configuring Hazelcast

server.xml

 1<!-- tag::copyright[] -->
 2<!--
 3     Copyright (c) 2019 IBM Corporation and others.
 4     All rights reserved. This program and the accompanying materials
 5     are made available under the terms of the Eclipse Public License
 6     v1.0 which accompanies this distribution, and is available at
 7     http://www.eclipse.org/legal/epl-v10.html
 8
 9     Contributors:
10         IBM Corporation - Initial implementation
11-->
12<!-- end::copyright[] -->
13<server description="Liberty Server for Sessions Management">
14
15    <featureManager>
16        <feature>servlet-4.0</feature>
17        <!-- tag::sessionCache[] -->
18        <feature>sessionCache-1.0</feature>
19        <!-- end::sessionCache[] -->
20        <feature>jaxrs-2.1</feature>
21        <feature>jsonp-1.1</feature>
22        <feature>mpOpenAPI-1.1</feature>
23    </featureManager>
24
25    <httpEndpoint httpPort="${default.http.port}" httpsPort="${default.https.port}"
26        id="defaultHttpEndpoint" host="*" />
27    <!-- tag::httpSessionCache[] -->
28    <httpSessionCache libraryRef="jCacheVendorLib"
29        uri="file:${shared.config.dir}/hazelcast-config.xml" />
30    <!-- end::httpSessionCache[] -->
31    <!-- tag::library[] -->
32    <library id="jCacheVendorLib">
33              <!-- tag::hazelcastjar[] -->
34        <file name="${shared.resource.dir}/hazelcast.jar" />
35        <!-- end::hazelcastjar[] -->
36    </library>
37    <!-- end::library[] -->
38
39    <webApplication location="cart-app.war" contextRoot="${app.context.root}" />
40
41</server>

By default, all Open Liberty servers that run the sessionCache feature and Hazelcast are connected using a peer-to-peer model.

You can share the session cache only among certain Hazelcast instances by using the <group /> configuration tag in the Hazelcast configuration file.

Create the hazelcast-config.xml configuration file.
src/main/liberty/config/hazelcast-config.xml

hazelcast-config.xml

 1<!-- tag::copyright[] -->
 2<!--
 3     Copyright (c) 2019 IBM Corporation and others.
 4     All rights reserved. This program and the accompanying materials
 5     are made available under the terms of the Eclipse Public License
 6     v1.0 which accompanies this distribution, and is available at
 7     http://www.eclipse.org/legal/epl-v10.html
 8
 9     Contributors:
10         IBM Corporation - Initial implementation
11-->
12<!-- end::copyright[] -->
13<hazelcast xmlns="http://www.hazelcast.com/schema/config"
14    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
15    xsi:schemaLocation="http://www.hazelcast.com/schema/config
16       https://hazelcast.com/schema/config/hazelcast-config.xsd">
17    <!-- tag::group[] -->
18    <group>
19    <!-- tag::cartCluster[] -->
20        <name>CartCluster</name>
21    <!-- end::cartCluster[] -->
22    </group>
23    <!-- end::group[] -->
24</hazelcast>

The cluster group CartCluster is defined in the hazelcast-config.xml.

In the server.xml file, a reference to the Hazelcast configuration file is made by using the httpSessionCache tag. The hazelcast-config.xml file is copied to the predefined {shared.resource.dir} directory when a Maven build runs. This goal is defined in the provided Maven POM file.

There are more configuration settings that you can explore in the Hazelcast documentation.

Building and running the application

To build the application, run the Maven install phase from the command line in the start directory:

mvn install

This command builds the application and creates a .war file in the target directory. It also configures and installs Open Liberty into the target/liberty/wlp directory.

Next, run the Maven liberty:start-server goal to start an Open Liberty server instance:

mvn liberty:start-server

Point your browser to the http://localhost:9080/openapi/ui/ URL. This URL displays the available REST endpoints.

First, make a POST request to the /cart/{item}&{price} endpoint. To make this request, expand the POST endpoint on the UI, click the Try it out button, provide an item and a price, and then click the Execute button. The POST request adds a user-specified item and price to a session that represents data in a user’s cart.

Next, make a GET request to /cart endpoint. To make this request, expand the GET endpoint on the UI, click the Try it out button, and then click the Execute button. The GET request returns a pod name, a session ID, and all the items from your session.

After you’re done checking out the application, stop the Open Liberty server:

mvn liberty:stop-server

Containerizing the application

Before you can deploy the application to Kubernetes, you need to containerize it with Docker.

The Dockerfile is provided at the start directory. If you’re unfamiliar with Dockerfile, check out the Containerizing microservices guide, which covers Dockerfile in depth.

Navigate to the start directory and run the following command:

docker build -t cart-app:1.0-SNAPSHOT .

When the build finishes, run the following command to list all local Docker images:

docker images

Verify that the cart-app:1.0-SNAPSHOT image is listed among the Docker images, for example:

REPOSITORY           TAG
cart-app             1.0-SNAPSHOT
open-liberty         latest

Deploying and running the application in Kubernetes

kubernetes.yaml

 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: cart-deployment
 5spec:
 6  selector:
 7    matchLabels:
 8      app: cart
 9  # tag::replicas[]
10  replicas: 3
11  # end::replicas[]
12  template:
13    metadata:
14      labels:
15        app: cart
16    spec:
17      containers:
18      - name: cart-container
19        image: cart-app:1.0-SNAPSHOT
20        ports:
21        - containerPort: 9080
22---
23apiVersion: v1
24kind: Service
25metadata:
26  name: cart-service
27spec:
28  type: NodePort
29  selector:
30    app: cart
31  ports:
32  - protocol: TCP
33    port: 9080
34    targetPort: 9080
35    nodePort: 31000

Now that the containerized application is built, deploy it to a local Kubernetes cluster by using a Kubernetes resource definition, which is provided in the kubernetes.yaml file at the start directory.

Run the following command to deploy the application into 3 replicated pods as defined in the kubernetes.yaml file:

kubectl apply -f kubernetes.yaml

When the application is deployed, run the following command to check the status of your pods:

kubectl get pods

You see an output similar to the following if all the pods are working correctly:

NAME                             READY  STATUS   RESTARTS  AGE
cart-deployment-98f4ff789-2xlhs  1/1    Running  0         17s
cart-deployment-98f4ff789-6rvfj  1/1    Running  0         17s
cart-deployment-98f4ff789-qrh45  1/1    Running  0         17s

Point your browser to the http://localhost:31000/openapi/ui/ URL. This URL displays the available REST endpoints.

Make a POST request to the /cart/{item}&{price} endpoint. To make this request, expand the POST endpoint on the UI, click the Try it out button, provide an item and a price, and then click the Execute button. The POST request adds a user-specified item and price to a session that represents data in a user’s cart.

Next, make a GET request to the /cart endpoint. To make this request, expand the GET endpoint on the UI, click the Try it out button, and then click the Execute button. The GET request returns a pod name, a session ID, and all the items from your session.

{
  "pod-name": "cart-deployment-98f4ff789-2xlhs",
  "session-id": "RyJKzmka6Yc-ZCMzEA8-uPq",
  "cart": [
    "eggs | $2.89"
  ],
  "subtotal": 2.89
}

Replace the [pod-name] in the following command, and then run the command to pause the pod for the GET request that you just ran:

kubectl exec -it [pod-name] /opt/ol/wlp/bin/server pause defaultServer

Repeat the GET request. You see the same session-id but a different pod-name because the session data is cached but the request is served by a different pod (server).

Verify that the Hazelcast cluster is running by checking the Open Liberty log. Run the following command:

kubectl exec -it [pod-name] cat /logs/messages.log

You see a message similar to the following:

... I [10.1.0.46]:5701 [CartCluster] [3.11.2]

Members {size:3, ver:3} [
	Member [10.1.0.40]:5701 - 01227d80-501e-4789-ae9d-6fb348d794ea
	Member [10.1.0.41]:5701 - a68d0ed1-f50e-4a4c-82b0-389f356b8c73 this
	Member [10.1.0.42]:5701 - b0dfa05a-c110-45ed-9424-adb1b2896a3d
]

You can resume the paused pod by running the following command:

kubectl exec -it [pod-name] /opt/ol/wlp/bin/server resume defaultServer

Tearing down the environment

When you no longer need your deployed application, you can delete all Kubernetes resources by running the kubectl delete command:

kubectl delete -f kubernetes.yaml

Nothing more needs to be done for Docker Desktop.

Perform the following steps to return your environment to a clean state.

  1. Point the Docker daemon back to your local machine:

    eval $(minikube docker-env -u)
  2. Stop your Minikube cluster:

    minikube stop
  3. Delete your cluster:

    minikube delete

Great work! You’re done!

You have created, used, and cached HTTP session data for an application that was running on Open Liberty server and deployed in a Kubernetes cluster.

Guide Attribution

Caching HTTP session data by Open Liberty is licensed under CC BY-ND 4.0

Copied to clipboard
Copy code block
Copy file contents

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star