Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/openliberty/guide-sessions
A guide on how to create, use, and cache HTTP session data for your application:
https://github.com/openliberty/guide-sessions
Last synced: 3 months ago
JSON representation
A guide on how to create, use, and cache HTTP session data for your application:
- Host: GitHub
- URL: https://github.com/openliberty/guide-sessions
- Owner: OpenLiberty
- License: other
- Created: 2018-06-21T17:05:03.000Z (over 6 years ago)
- Default Branch: prod
- Last Pushed: 2024-08-14T13:13:08.000Z (5 months ago)
- Last Synced: 2024-08-14T14:37:33.790Z (5 months ago)
- Language: Java
- Homepage: https://openliberty.io/guides/sessions.html
- Size: 14.5 MB
- Stars: 4
- Watchers: 5
- Forks: 12
- Open Issues: 3
-
Metadata Files:
- Readme: README.adoc
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
// Copyright (c) 2019, 2024 IBM Corporation and others.
// Licensed under Creative Commons Attribution-NoDerivatives
// 4.0 International (CC BY-ND 4.0)
// https://creativecommons.org/licenses/by-nd/4.0/
//
// Contributors:
// IBM Corporation
//
:page-layout: guide-multipane
:projectid: sessions
:page-duration: 25 minutes
:page-releasedate: 2019-07-23
:page-description: Learn how to create, use and cache HTTP session data.
:guide-author: Open Liberty
:page-tags: ['docker']
:page-related-guides: ['rest-intro', 'microprofile-openapi', 'kubernetes-intro']
:page-permalink: /guides/{projectid}
:common-includes: https://raw.githubusercontent.com/OpenLiberty/guides-common/prod
:imagesdir: /img/guide/{projectid}
:page-seo-title: Caching HTTP session data using JCache and Hazelcast
:page-seo-description: A getting started tutorial with examples on how to create, use, and cache HTTP session data for an enterprise Java application on a Kubernetes cluster by using Java Caching (JCache).
= Caching HTTP session data using JCache and HazelcastLearn how to create, use, and cache HTTP session data for your application.
:kube: Kubernetes
:win: WINDOWS
:mac: MAC
:linux: LINUX// =================================================================================================
// Introduction
// =================================================================================================
== What you'll learn=== What is a session?
// *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?
// *Session caching* +
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.image::sessionCache.png[Session Cache,width=100%]
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.// =================================================================================================
// Prerequisites
// =================================================================================================
[role='command']
include::{common-includes}/kube-prereq.adoc[]// =================================================================================================
// Getting Started
// =================================================================================================
[role="command"]
include::{common-includes}/gitclone.adoc[]== 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 Open Liberty instances by using the
`sessionCache` feature. 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.
[role="code_command hotspot file=0", subs="quotes"]
----
#Create the `CartApplication` class.#
`src/main/java/io/openliberty/guides/cart/CartApplication.java`
----
CartApplication.java
[source, Java, linenums, indent=0, role="code_column hide_tags=copyright"]
----
include::finish/src/main/java/io/openliberty/guides/cart/CartApplication.java[]
----The [hotspot file=0]`CartApplication` class extends the generic JAX-RS application class that is needed to run the
application.[role="code_command hotspot file=1", subs="quotes"]
----
#Create the `CartResource` class.#
`src/main/java/io/openliberty/guides/cart/CartResource.java`
----
CartResource.java
[source, Java, linenums, indent=0, role="code_column hide_tags=copyright"]
----
include::finish/src/main/java/io/openliberty/guides/cart/CartResource.java[]
----The [hotspot file=1]`CartResource` class defines the REST endpoints at which a user can make
an HTTP request.The [hotspot=addToCart file=1]`addToCart` and [hotspot=getCart file=1]`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
https://openliberty.io/guides/microprofile-openapi.html#augmenting-the-existing-jax-rs-annotations-with-openapi-annotations[Documenting RESTful APIs^]
and
https://openliberty.io/guides/rest-intro.html#creating-a-jax-rs-application[Creating a RESTful web service^]
guides.The [hotspot=endpointCartItemPrice file=1]`cart/{item}&{price}` endpoint demonstrates how to set session data.
The [hotspot=item hotspot=price file=1]`@PathParam` annotation injects a custom [hotspot=item file=1]`item` and
[hotspot=price file=1]`price` from the POST request into the method parameter.
The [hotspot=addToCart file=1]`addToCart` method gets the current [hotspot=getSession file=1]`session` and binds
the `{item}:{price}` key-value pair into the session by the [hotspot=setAttribute file=1]`setAttribute()` method.
A response is then built and returned to confirm that an item was added to your cart and session.The [hotspot=endpointCart file=1]`cart` endpoint demonstrates how to get session data.
The [hotspot=getCart file=1]`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 Liberty instance by
[hotspot=podname file=1]`pod-name`, the session by [hotspot=sessionid file=1]`session-id`,
and the items in your cart by [hotspot=cart file=1]`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 instance can act as the JCache client and connect
to a dedicated JCache server.
* Peer-to-peer model: A Liberty instance can connect with other Liberty instances
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 [hotspot=sessionCache]`sessionCache` feature uses JCache, which allows for session
persistence by providing a common cache of session data between Liberty instances.
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 [hotspot=sessionCache]`sessionCache` feature is enabled.[role="code_command hotspot", subs="quotes"]
----
#Create the Liberty `server.xml` configuration file.#
`src/main/liberty/config/server.xml`
----server.xml
[source, xml, linenums, indent=0, role="code_column hide_tags=copyright"]
----
include::finish/src/main/liberty/config/server.xml[]
----pom.xml
[source, xml, linenums, indent=0, role="code_column hide_tags=copyright"]
----
include::finish/pom.xml[]
----The [hotspot=library file=0]`library` element includes the library reference that indicates
to the Liberty where the Hazelcast implementation of JCache is located.
Your Hazelcast implementation of JCache is a JAR file that resides in the shared resources directory that is defined by the [hotspot=hazelcastjar file=0]`file` element.
The `hazelcast-*.jar` file is downloaded by the Liberty Maven plugin. The [hotspot=configuration file=1]`configuration` is defined in the provided Maven POM file.=== Configuring Hazelcast
server.xml
[source, xml, linenums, indent=0, role="code_column hide_tags=copyright"]
----
include::finish/src/main/liberty/config/server.xml[]
----By default, all Open Liberty instances that run the [hotspot=sessionCache file=0]`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 `cluster-name` configuration element in the Hazelcast configuration file.[role="code_command hotspot file=1", subs="quotes"]
----
#Create the `hazelcast-config.xml` configuration file.#
`src/main/liberty/config/hazelcast-config.xml`
----hazelcast-config.xml
[source, xml, linenums, indent=0, role="code_column hide_tags=copyright"]
----
include::finish/src/main/liberty/config/hazelcast-config.xml[]
----The [hotspot=cartCluster file=1]`CartCluster` cluster name is defined in the [hotspot file=1]`hazelcast-config.xml` file. To allow Hazelcast cluster members to find each other, enable the [hotspot=multicast file=1]`multicast` communication in the [hotspot=network file=1]`network` configuration.
In the [hotspot file=0]`server.xml` configuration file, a reference to the Hazelcast configuration file is made by using
the [hotspot=httpSessionCache file=0]`httpSessionCache` tag.[role="code_command hotspot file=2", subs="quotes"]
----
#Create the `bootstrap.properties` file.#
`src/main/liberty/config/bootstrap.properties`
----bootstrap.properties
[source, text, linenums, indent=0, role="code_column"]
----
include::finish/src/main/liberty/config/bootstrap.properties[]
----Hazelcast JCache provides the client and member providers. Set `hazelcast.jcache.provider.type` to `member` to use the member provider.
There are more configuration settings that you can explore in the
https://docs.hazelcast.org/docs/latest/manual/html-single/#understanding-configuration[Hazelcast documentation^].// =================================================================================================
// Running the application
// =================================================================================================== Running the application
[role="command"]
include::{common-includes}/devmode-lmp33-start.adoc[]Point your browser to the link:http://localhost:9090/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 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.[role='command']
include::{common-includes}/devmode-quit-ctrlc.adoc[]// =================================================================================================
// Staring and preparing your cluster for deployment
// =================================================================================================
[role='command']
include::{common-includes}/kube-start.adoc[]== Containerizing the application
Before you can deploy the application to Kubernetes, you need to containerize it with Docker.
Make sure to start your Docker daemon before you proceed.
The Dockerfile is provided at the `start` directory. If you're unfamiliar with Dockerfile,
check out the https://openliberty.io/guides/containerize.html[Containerizing microservices^] guide,
which covers Dockerfile in depth.Run the `mvn package` command from the `start` directory so that the `.war` file resides in the `target` directory.
[role='command']
```
mvn package
```To build and containerize the application, run the following Docker build command in the `start` directory:
[role='command']
```
docker build -t cart-app:1.0-SNAPSHOT .
```When the build finishes, run the following command to list all local Docker images:
[role='command']
```
docker images
```Verify that the `cart-app:1.0-SNAPSHOT` image is listed among the Docker images, for example:
[source, role="no_copy"]
----
REPOSITORY TAG
cart-app 1.0-SNAPSHOT
icr.io/appcafe/open-liberty kernel-slim-java11-openj9-ubi
----== Deploying and running the application in Kubernetes
kubernetes.yaml
[source, yaml, linenums, role='code_column']
----
include::finish/kubernetes.yaml[]
----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 [hotspot file=0]`kubernetes.yaml` file
at the `start` directory.First, use the `ClusterRoleBinding` Kubernetes API object to grant Hazelcast members to access the cluster.
[role='command']
```
kubectl apply -f https://raw.githubusercontent.com/hazelcast/hazelcast/master/kubernetes-rbac.yaml
```Run the following command to deploy the application into [hotspot=replicas file=0]`3` replicated pods as defined
in the `kubernetes.yaml` file:
[role='command']
```
kubectl apply -f kubernetes.yaml
```When the application is deployed, run the following command to check the status of your pods:
[role='command']
```
kubectl get pods
```You see an output similar to the following if all the pods are working correctly:
[role="no_copy"]
----
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
----include::{common-includes}/os-tabs.adoc[]
[.tab_content.windows_section.mac_section]
--
Point your browser to the link:http://localhost:31000/openapi/ui/[^] URL.
This URL displays the available REST endpoints.
--[.tab_content.linux_section]
--
Run the `minikube ip` command to get the hostname for minikube.
Then, go to the `http://[hostname]:31000/openapi/ui/` URL in your browser.
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.[role="no_copy"]
----
{
"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:[role='command']
```
kubectl exec -it [pod-name] -- /opt/ol/wlp/bin/server pause
```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 (Liberty instance).Verify that the Hazelcast cluster is running by checking the Open Liberty log.
To check the log, run the following command:[role='command']
```
kubectl exec -it [pod-name] -- cat /logs/messages.log
```You see a message similar to the following:
[role="no_copy"]
----
... [10.1.0.46]:5701 [CartCluster] [5.3.0]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:
[role='command']
```
kubectl exec -it [pod-name] -- /opt/ol/wlp/bin/server resume
```// =================================================================================================
// Tear Down
// =================================================================================================== Tearing down the environment
When you no longer need your deployed application, you can delete all {kube} resources and disable the Hazelcast members' access to the cluster by running the `kubectl delete` commands:
[role='command']
```
kubectl delete -f kubernetes.yaml
kubectl delete -f https://raw.githubusercontent.com/hazelcast/hazelcast/master/kubernetes-rbac.yaml
```[role='command']
include::{common-includes}/kube-minikube-teardown.adoc[]== Great work! You're done!
You have created, used, and cached HTTP session data for an application that was running on Open Liberty
and deployed in a Kubernetes cluster.include::{common-includes}/attribution.adoc[subs="attributes"]