Fix minor documentation errors

Fix minor documentation errors

= Spring Session
Rob Winch
:doctype: book
:indexdoc-tests: {docs-test-dir}docs/IndexDocTests.java
:websocketdoc-test-dir: {docs-test-dir}docs/websocket/
:toc: left

[[abstract]]

Spring Session provides an API and implementations for managing a user's session information.

[[introduction]]
== Introduction

Spring Session provides an API and implementations for managing a user's session information. It also provides transparent integration with:

* <<httpsession,HttpSession>> - allows replacing the HttpSession in an application container (i.e. Tomcat) neutral way.
Additional features include:
** **Clustered Sessions** - Spring Session makes it trivial to support <<httpsession-redis,clustered sessions>> without being tied to an application container specific solution.
** **Multiple Browser Sessions** - Spring Session supports <<httpsession-multi,managing multiple users' sessions>> in a single browser instance (i.e. multiple authenticated accounts similar to Google).
** **RESTful APIs** - Spring Session allows providing session ids in headers to work with <<httpsession-rest,RESTful APIs>>

* <<websocket,WebSocket>> - provides the ability to keep the `HttpSession` alive when receiving WebSocket messages

== What's New in 1.1

Below are the highlights of what is new in Spring Session 1.1. You can find a complete list of what's new in https://github.com/spring-projects/spring-session/issues?utf8=%E2%9C%93&q=milestone%3A%221.1.0+M1%22[1.1.0 M1] and https://github.com/spring-projects/spring-session/issues?utf8=%E2%9C%93&q=milestone%3A%221.1.0+RC1%22[1.1.0 RC1] by referring to the changelog.

* https://github.com/spring-projects/spring-session/issues/148[#148] - Added <<httpsession-gemfire,GemFire Support>>
* https://github.com/spring-projects/spring-session/issues/7[#7] - link:guides/findbyusername.html[Query by Username]
* https://github.com/spring-projects/spring-session/issues/299[#299] - link:guides/custom-cookie.html[Customize Cookie Creation]
* https://github.com/spring-projects/spring-session/issues/4[#4] - Add <<httpsession-httpsessionlistener,HttpSessionListener>> support
* https://github.com/spring-projects/spring-session/issues/283[#283] - Allow override default `RedisSerializer`
* https://github.com/spring-projects/spring-session/issues/277[#277] - Added link:guides/hazelcast-spring.html[@EnableHazelcastHttpSession]
* https://github.com/spring-projects/spring-session/issues/271[#271] - Performance improvements
* https://github.com/spring-projects/spring-session/pull/218[#218] - Allow scoping the session in Redis using <<api-redisoperationssessionrepository-config,redisNamespace>>
* https://github.com/spring-projects/spring-session/issues/273[#273] - Allow writing to Redis immediately (instead of lazily) using <<api-redisoperationssessionrepository-config,redisFlushMode>>
* https://github.com/spring-projects/spring-session/issues/272[#272] - Add `ExpiringSession.setLastAccessedTime(long)`
* https://github.com/spring-projects/spring-session/pull/349[#349] - Added https://gitter.im/spring-projects/spring-session[Gitter Room] for discussing Spring Session

[[samples]]
== Samples and Guides (Start Here)

If you are looking to get started with Spring Session, the best place to start is our Sample Applications.

.Sample Applications
|===
| Source | Description | Guide

| {gh-samples-url}httpsession[HttpSession]
| Demonstrates how to use Spring Session to replace the `HttpSession` with a Redis store.
| link:guides/httpsession.html[HttpSession Guide]

| {gh-samples-url}httpsession-xml[HttpSession XML]
| Demonstrates how to use Spring Session to replace the `HttpSession` with a Redis store using XML based configuration.
| link:guides/httpsession-xml.html[HttpSession XML Guide]

| {gh-samples-url}httpsession-gemfire-clientserver[HttpSession with GemFire (Client/Server)]
| Demonstrates how to use Spring Session to replace the `HttpSession` with GemFire using a Client/Server topology.
| link:guides/httpsession-gemfire-clientserver.html[HttpSession GemFire Client/Server Guide]

| {gh-samples-url}httpsession-gemfire-clientserver-xml[HttpSession with GemFire (Client/Server) using XML]
| Demonstrates how to use Spring Session to replace the `HttpSession` with GemFire using a Client/Server topology configured with XML.
| link:guides/httpsession-gemfire-clientserver-xml.html[HttpSession GemFire Client/Server XML Guide]

| {gh-samples-url}httpsession-gemfire-p2p[HttpSession with GemFire (P2P)]
| Demonstrates how to use Spring Session to replace the `HttpSession` with GemFire using a P2P topology.
| link:guides/httpsession-gemfire-p2p.html[HttpSession GemFire P2P Guide]

| {gh-samples-url}httpsession-gemfire-p2p-xml[HttpSession with GemFire (P2P) using XML]
| Demonstrates how to use Spring Session to replace the `HttpSession` with GemFire using a P2P topology configured with XML.
| link:guides/httpsession-gemfire-p2p-xml.html[HttpSession GemFire P2P XML Guide]

| {gh-samples-url}custom-cookie[Custom Cookie]
| Demonstrates how to use Spring Session and customize the cookie.
| link:guides/custom-cookie.html[Custom Cookie Guide]

| {gh-samples-url}boot[Spring Boot]
| Demonstrates how to use Spring Session with Spring Boot.
| link:guides/boot.html[Spring Boot Guide]

| {gh-samples-url}security[Spring Security]
| Demonstrates how to use Spring Session with an existing Spring Security application.
| link:guides/security.html[Spring Security Guide]

| {gh-samples-url}rest[REST]
| Demonstrates how to use Spring Session in a REST application to support authenticating with a header.
| link:guides/rest.html[REST Guide]

| {gh-samples-url}findbyusername[Find by Username]
| Demonstrates how to use Spring Session to find sessions by username.
| link:guides/findbyusername.html[Find by Username]

| {gh-samples-url}users[Multiple Users]
| Demonstrates how to use Spring Session to manage multiple simultaneous browser sessions (i.e Google Accounts).
| link:guides/users.html[Manage Multiple Users Guide]

| {gh-samples-url}websocket[WebSocket]
| Demonstrates how to use Spring Session with WebSockets.
| link:guides/websocket.html[WebSocket Guide]

[[samples-hazelcast]]
| {gh-samples-url}hazelcast[Hazelcast]
| Demonstrates how to use Spring Session with Hazelcast.
| TBD

[[samples-hazelcast-spring]]
| {gh-samples-url}hazelcast-spring[Hazelcast Spring]
| Demonstrates how to use Spring Session and Hazelcast with an existing Spring Security application.
| link:guides/hazelcast-spring.html[Hazelcast Spring Guide]

|===

[[httpsession]]
== HttpSession Integration

Spring Session provides transparent integration with `HttpSession`.
This means that developers can switch the `HttpSession` implementation out with an implementation that is backed by Spring Session.

[[httpsession-why]]
=== Why Spring Session & HttpSession?

We have already mentioned that Spring Session provides transparent integration with `HttpSession`, but what benefits do we get out of this?

* **Clustered Sessions** - Spring Session makes it trivial to support <<httpsession-redis,clustered sessions>> without being tied to an application container specific solution.
* **Multiple Browser Sessions** - Spring Session supports <<httpsession-multi,managing multiple users' sessions>> in a single browser instance (i.e. multiple authenticated accounts similar to Google).
* **RESTful APIs** - Spring Session allows providing session ids in headers to work with <<httpsession-rest,RESTful APIs>>

[[httpsession-redis]]
=== HttpSession with Redis

Using Spring Session with `HttpSession` is enabled by adding a Servlet Filter before anything that uses the `HttpSession`.
You can choose from enabling this using either:

* <<httpsession-redis-jc,Java Based Configuration>>
* <<httpsession-redis-xml,XML Based Configuration>>

[[httpsession-redis-jc]]
==== Redis Java Based Configuration

This section describes how to use Redis to back `HttpSession` using Java based configuration.

NOTE: The <<samples, HttpSession Sample>> provides a working sample on how to integrate Spring Session and `HttpSession` using Java configuration.
You can read the basic steps for integration below, but you are encouraged to follow along with the detailed HttpSession Guide when integrating with your own application.

include::guides/httpsession.adoc[tags=config,leveloffset=+3]

[[httpsession-redis-xml]]
==== Redis XML Based Configuration

This section describes how to use Redis to back `HttpSession` using XML based configuration.

NOTE: The <<samples, HttpSession XML Sample>> provides a working sample on how to integrate Spring Session and `HttpSession` using XML configuration.
You can read the basic steps for integration below, but you are encouraged to follow along with the detailed HttpSession XML Guide when integrating with your own application.

include::guides/httpsession-xml.adoc[tags=config,leveloffset=+3]

[[httpsession-gemfire]]
=== HttpSession with Pivotal GemFire

When https://pivotal.io/big-data/pivotal-gemfire[Pivotal GemFire] is used with Spring Session, a web application's
`HttpSession` can be replaced with a **clustered** implementation managed by GemFire and conveniently accessed
with Spring Session's API.

The two most common topologies to manage Spring Sessions using GemFire include:

* <<httpsession-gemfire-clientserver,Client-Server>>
* <<httpsession-gemfire-p2p,Peer-To-Peer (P2P)>>

Additionally, GemFire supports site-to-site replication using http://gemfire.docs.pivotal.io/docs-gemfire/topologies_and_comm/multi_site_configuration/chapter_overview.html[WAN functionality].
The ability to configure and use GemFire's WAN support is independent of Spring Session, and is beyond the scope
of this document. More details on GemFire WAN functionality can be found http://docs.spring.io/spring-data-gemfire/docs/current/reference/html/#bootstrap:gateway[here].

[[httpsession-gemfire-clientserver]]
==== GemFire Client-Server

The http://gemfire.docs.pivotal.io/docs-gemfire/latest/topologies_and_comm/cs_configuration/chapter_overview.html[Client-Server]
topology will probably be the more common configuration preference for users when using GemFire as a provider in
Spring Session since a GemFire server will have significantly different and unique JVM heap requirements when compared
to the application. Using a client-server topology enables an application to manage (e.g. replicate) application state
independently from other application processes.

In a client-server topology, an application using Spring Session will open a client cache connection to a (remote)
GemFire server cluster to manage and provide consistent access to all `HttpSession` state.

You can configure a Client-Server topology with either:

* <<httpsession-gemfire-clientserver-java,Java-based Configuration>>
* <<httpsession-gemfire-clientserver-xml,XML-based Configuration>>

[[httpsession-gemfire-clientserver-java]]
===== GemFire Client-Server Java-based Configuration

This section describes how to use GemFire's Client-Server topology to back an `HttpSession` with Java-based configuration.

NOTE: The <<samples,HttpSession with GemFire (Client-Server) Sample>> provides a working sample on how to integrate
Spring Session and GemFire to replace the HttpSession using Java configuration. You can read the basic steps for
integration below, but you are encouraged to follow along with the detailed HttpSession with GemFire (Client-Server)
Guide when integrating with your own application.

include::guides/httpsession-gemfire-clientserver.adoc[tags=config,leveloffset=+3]

[[http-session-gemfire-clientserver-xml]]
===== GemFire Client-Server XML-based Configuration

This section describes how to use GemFire's Client-Server topology to back an `HttpSession` with XML-based configuration.

NOTE: The <<samples,HttpSession with GemFire (Client-Server) using XML Sample>> provides a working sample on how to
integrate Spring Session and GemFire to replace the `HttpSession` using XML configuration. You can read the basic steps
for integration below, but you are encouraged to follow along with the detailed HttpSession with GemFire (Client-Server)
using XML Guide when integrating with your own application.

include::guides/httpsession-gemfire-clientserver-xml.adoc[tags=config,leveloffset=+3]

[[httpsession-gemfire-p2p]]
==== GemFire Peer-To-Peer (P2P)

Perhaps less common would be to configure the Spring Session application as a peer member in the GemFire cluster using
the http://gemfire.docs.pivotal.io/docs-gemfire/latest/topologies_and_comm/p2p_configuration/chapter_overview.html[Peer-To-Peer (P2P)] topology.
In this configuration, a Spring Session application would be an actual data node (server) in the GemFire cluster,
and **not** a cache client as before.

One advantage to this approach is the proximity of the application to the application's state (i.e. it's data). However,
there are other effective means of accomplishing similar data dependent computations, such as using GemFire's
http://gemfire.docs.pivotal.io/docs-gemfire/latest/developing/function_exec/chapter_overview.html[Function Execution].
Any of GemFire's other http://gemfire.docs.pivotal.io/docs-gemfire/latest/getting_started/product_intro.html[features]
can be used when GemFire is serving as a provider in Spring Session.

P2P is very useful for both testing purposes as well as smaller, more focused and self-contained applications,
such as those found in a microservices architecture, and will most certainly improve on your application's latency,
throughput and consistency needs.

You can configure a Peer-To-Peer (P2P) topology with either:

* <<httpsession-gemfire-p2p-java,Java-based Configuration>>
* <<httpsession-gemfire-p2p-xml,XML-based Configuration>>

[[httpsession-gemfire-p2p-java]]
===== GemFire Peer-To-Peer (P2P) Java-based Configuration

This section describes how to use GemFire's Peer-To-Peer (P2P) topology to back an `HttpSession` using Java-based configuration.

NOTE: The <<samples, HttpSession with GemFire (P2P) Sample>> provides a working sample on how to integrate
Spring Session and GemFire to replace the `HttpSession` using Java configuration. You can read the basic steps
for integration below, but you are encouraged to follow along with the detailed HttpSession with GemFire (P2P) Guide
when integrating with your own application.

include::guides/httpsession-gemfire-p2p.adoc[tags=config,leveloffset=+3]

[[httpsession-gemfire-p2p-xml]]
===== GemFire Peer-To-Peer (P2P) XML-based Configuration

This section describes how to use GemFire's Peer-To-Peer (P2P) topology to back an `HttpSession` using XML-based configuration.

NOTE: The <<samples, HttpSession with GemFire (P2P) using XML Sample>> provides a working sample on how to integrate
Spring Session and GemFire to replace the `HttpSession` using XML configuration. You can read the basic steps for
integration below, but you are encouraged to follow along with the detailed HttpSession with GemFire (P2P) using XML
Guide when integrating with your own application.

include::guides/httpsession-gemfire-p2p-xml.adoc[tags=config,leveloffset=+3]

[[httpsession-how]]
=== How HttpSession Integration Works

Fortunately both `HttpSession` and `HttpServletRequest` (the API for obtaining an `HttpSession`) are both interfaces.
This means that we can provide our own implementations for each of these APIs.

NOTE: This section describes how Spring Session provides transparent integration with `HttpSession`. The intent is so that user's can understand what is happening under the covers. This functionality is already integrated and you do NOT need to implement this logic yourself.

First we create a custom `HttpServletRequest` that returns a custom implementation of `HttpSession`.
It looks something like the following:

[source, java]
----
public class SessionRepositoryRequestWrapper extends HttpServletRequestWrapper {

	public SessionRepositoryRequestWrapper(HttpServletRequest original) {
		super(original);
	}

	public HttpSession getSession() {
		return getSession(true);
	}

	public HttpSession getSession(boolean createNew) {
		// create an HttpSession implementation from Spring Session
	}

	// ... other methods delegate to the original HttpServletRequest ...
}
----

Any method that returns an `HttpSession` is overridden.
All other methods are implemented by `HttpServletRequestWrapper` and simply delegate to the original `HttpServletRequest` implementation.

We replace the `HttpServletRequest` implementation using a servlet `Filter` called `SessionRepositoryFilter`.
The pseudocode can be found below:

[source, java]
----
public class SessionRepositoryFilter implements Filter {

	public doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		SessionRepositoryRequestWrapper customRequest =
			new SessionRepositoryRequestWrapper(httpRequest);

		chain.doFilter(customRequest, response, chain);
	}

	// ...
}
----

By passing in a custom `HttpServletRequest` implementation into the `FilterChain` we ensure that anything invoked after our `Filter` uses the custom `HttpSession` implementation.
This highlights why it is important that Spring Session's `SessionRepositoryFilter` must be placed before anything that interacts with the `HttpSession`.

[[httpsession-multi]]
=== Multiple HttpSessions in Single Browser

Spring Session has the ability to support multiple sessions in a single browser instance.
This provides the ability to support authenticating with multiple users in the same browser instance (i.e. Google Accounts).

NOTE: The <<samples,Manage Multiple Users Guide>> provides a complete working example of managing multiple users in the same browser instance.
You can follow the basic steps for integration below, but you are encouraged to follow along with the detailed Manage Multiple Users Guide when integrating with your own application.

include::guides/users.adoc[tags=how-does-it-work,leveloffset=+1]

[[httpsession-rest]]
=== HttpSession & RESTful APIs

Spring Session can work with RESTful APIs by allowing the session to be provided in a header.

NOTE: The <<samples, REST Sample>> provides a working sample on how to use Spring Session in a REST application to support authenticating with a header.
You can follow the basic steps for integration below, but you are encouraged to follow along with the detailed REST Guide when integrating with your own application.

include::guides/rest.adoc[tags=config,leveloffset=+2]

[[httpsession-httpsessionlistener]]
=== HttpSessionListener

Spring Session supports `HttpSessionListener` by translating `SessionDestroyedEvent` and `SessionCreatedEvent` into `HttpSessionEvent` by declaring `SessionEventHttpSessionListenerAdapter`.
To use this support, you need to:

* Ensure your `SessionRepository` implementation supports and is configured to fire `SessionDestroyedEvent` and `SessionCreatedEvent`.
* Configure `SessionEventHttpSessionListenerAdapter` as a Spring bean.
* Inject every `HttpSessionListener` into the `SessionEventHttpSessionListenerAdapter`

If you are using the configuration support documented in <<httpsession-redis,HttpSession with Redis>>, then all you need to do is register every `HttpSessionListener` as a bean.
For example, assume you want to support Spring Security's concurrency control and need to use `HttpSessionEventPublisher` you can simply add `HttpSessionEventPublisher` as a bean.
In Java configuration, this might look like:

[source,java,indent=0]
----
include::{docs-test-dir}docs/http/RedisHttpSessionConfig.java[tags=config]
----

In XML configuration, this might look like:

[source,xml,indent=0]
----
include::{docs-test-resources-dir}docs/http/HttpSessionListenerXmlTests-context.xml[tags=config]
----

[[websocket]]
== WebSocket Integration

Spring Session provides transparent integration with Spring's WebSocket support.

include::guides/websocket.adoc[tags=disclaimer,leveloffset=+1]

[[websocket-why]]
=== Why Spring Session & WebSockets?

So why do we need Spring Session when using WebSockets?

Consider an email application that does much of its work through HTTP requests.
However, there is also a chat application embedded within it that works over WebSocket APIs.
If a user is actively chatting with someone, we should not timeout the `HttpSession` since this would be pretty poor user experience.
However, this is exactly what https://java.net/jira/browse/WEBSOCKET_SPEC-175[JSR-356] does.

Another issue is that according to JSR-356 if the `HttpSession` times out any WebSocket that was created with that HttpSession and an authenticated user should be forcibly closed.
This means that if we are actively chatting in our application and are not using the HttpSession, then we will also disconnect from our conversation!

[[websocket-usage]]
=== WebSocket Usage

The <<samples, WebSocket Sample>> provides a working sample on how to integrate Spring Session with WebSockets.
You can follow the basic steps for integration below, but you are encouraged to follow along with the detailed WebSocket Guide when integrating with your own application:

[[websocket-httpsession]]
==== HttpSession Integration

Before using WebSocket integration, you should be sure that you have <<httpsession>> working first.

include::guides/websocket.adoc[tags=config,leveloffset=+2]

[[api]]
== API Documentation

You can browse the complete link:../../api/[Javadoc] online. The key APIs are described below:

[[api-session]]
=== Session

A `Session` is a simplified `Map` of name value pairs.

Typical usage might look like the following:

[source,java,indent=0]
----
include::{indexdoc-tests}[tags=repository-demo]
----

<1> We create a `SessionRepository` instance with a generic type, `S`, that extends `Session`. The generic type is defined in our class.
<2> We create a new `Session` using our `SessionRepository` and assign it to a variable of type `S`.
<3> We interact with the `Session`. In our example, we demonstrate saving a `User` to the `Session`.
<4> We now save the `Session`. This is why we needed the generic type `S`. The `SessionRepository` only allows saving `Session` instances that were created or retrieved using the same `SessionRepository`. This allows for the `SessionRepository` to make implementation specific optimizations (i.e. only writing attributes that have changed).
<5> We retrieve the `Session` from the `SessionRepository`.
<6> We obtain the persisted `User` from our `Session` without the need for explicitly casting our attribute.

[[api-expiringsession]]
=== ExpiringSession

An `ExpiringSession` extends a `Session` by providing attributes related to the `Session` instance's expiration.
If there is no need to interact with the expiration information, prefer using the more simple `Session` API.

Typical usage might look like the following:

[source,java,indent=0]
----
include::{indexdoc-tests}[tags=expire-repository-demo]
----

<1> We create a `SessionRepository` instance with a generic type, `S`, that extends `ExpiringSession`. The generic type is defined in our class.
<2> We create a new `ExpiringSession` using our `SessionRepository` and assign it to a variable of type `S`.
<3> We interact with the `ExpiringSession`.
In our example, we demonstrate updating the amount of time the `ExpiringSession` can be inactive before it expires.
<4> We now save the `ExpiringSession`.
This is why we needed the generic type `S`.
The `SessionRepository` only allows saving `ExpiringSession` instances that were created or retrieved using the same `SessionRepository`.
This allows for the `SessionRepository` to make implementation specific optimizations (i.e. only writing attributes that have changed).
The last accessed time is automatically updated when the `ExpiringSession` is saved.
<5> We retrieve the `ExpiringSession` from the `SessionRepository`.
If the `ExpiringSession` were expired, the result would be null.

[[api-sessionrepository]]
=== SessionRepository

A `SessionRepository` is in charge of creating, retrieving, and persisting `Session` instances.

If possible, developers should not interact directly with a `SessionRepository` or a `Session`.
Instead, developers should prefer interacting with `SessionRepository` and `Session` indirectly through the <<httpsession,HttpSession>> and <<websocket,WebSocket>> integration.

[[api-findbyindexnamesessionrepository]]
=== FindByIndexNameSessionRepository

Spring Session's most basic API for using a `Session` is the `SessionRepository`.
This API is intentionally very simple, so that it is easy to provide additional implementations with basic functionality.

Some `SessionRepository` implementations may choose to implement `FindByIndexNameSessionRepository` also.
For example, Spring's Redis support implements `FindByIndexNameSessionRepository`.

The `FindByIndexNameSessionRepository` adds a single method to look up all the sessions for a particular user.
This is done by ensuring that the session attribute with the name `FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME` is populated with the username.
It is the responsibility of the developer to ensure the attribute is populated since Spring Session is not aware of the authentication mechanism being used.
An example of how this might be used can be seen below:

[source,java,indent=0]
----
include::{docs-test-dir}docs/FindByIndexNameSessionRepositoryTests.java[tags=set-username]
----

[NOTE]
====
Some implementations of `FindByIndexNameSessionRepository` will provide hooks to automatically index other session attributes.
For example, many implementations will automatically ensure the current Spring Security user name is indexed with the index name `FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME`.
====

Once the session is indexed, it can be found using the following:

[source,java,indent=0]
----
include::{docs-test-dir}docs/FindByIndexNameSessionRepositoryTests.java[tags=findby-username]
----

[[api-enablespringhttpsession]]
=== EnableSpringHttpSession

The `@EnableSpringHttpSession` annotation can be added to an `@Configuration` class to expose the `SessionRepositoryFilter` as a bean named "springSessionRepositoryFilter".
In order to leverage the annotation, a single `SessionRepository` bean must be provided.
For example:

[source,java,indent=0]
----
include::{docs-test-dir}docs/SpringHttpSessionConfig.java[tags=class]
----

It is important to note that no infrastructure for session expirations is configured for you out of the box.
This is because things like session expiration are highly implementation dependent.
This means if you require cleaning up expired sessions, you are responsible for cleaning up the expired sessions.

[[api-enablehazelcasthttpsession]]
=== EnableHazelcastHttpSession

If you wish to use http://hazelcast.org/[Hazelcast] as your backing source for the `SessionRepository`, then the `@EnableHazelcastHttpSession` annotation
can be added to an `@Configuration` class. This extends the functionality provided by the `@EnableSpringHttpSession` annotation but makes the `SessionRepository` for you in Hazelcast.
You must provide a single `HazelcastInstance` bean for the configuration to work.
For example:

[source,java,indent=0]
----
include::{docs-test-dir}docs/http/HazelcastHttpSessionConfig.java[tags=config]
----

This will configure Hazelcast in embedded mode with default configuration.
See the http://docs.hazelcast.org/docs/latest/manual/html-single/index.html#hazelcast-configuration[Hazelcast documentation] for
detailed information on configuration options for Hazelcast.

[[api-enablehazelcasthttpsession-storage]]
==== Storage Details

Sessions will be stored in a distributed `Map` in Hazelcast using a <<api-mapsessionrepository,MapSessionRepository>>.
The `Map` interface methods will be used to `get()` and `put()` Sessions.
The expiration of a session in the `Map` is handled by Hazelcast's support for setting the time to live on an entry when it is `put()` into the `Map`. Entries (sessions) that have been idle longer than the time to live will be automatically removed from the `Map`.

You shouldn't need to configure any settings such as `max-idle-seconds` or `time-to-live-seconds` for the `Map` within the Hazelcast configuration.

[[api-enablehazelcasthttpsession-customize]]
==== Basic Customization
You can use the following attributes on `@EnableHazelcastHttpSession` to customize the configuration:

* **maxInactiveIntervalInSeconds** - the amount of time before the session will expire in seconds. Default is 1800 seconds (30 minutes)
* **sessionMapName** - the name of the distributed `Map` that will be used in Hazelcast to store the session data.

[[api-enablehazelcasthttpsession-events]]
==== Session Events
Using a `MapListener` to respond to entries being added, evicted, and removed from the distributed `Map`, these events will trigger
publishing SessionCreatedEvent, SessionExpiredEvent, and SessionDeletedEvent events respectively using the `ApplicationEventPublisher`.

[[api-redisoperationssessionrepository]]
=== RedisOperationsSessionRepository

`RedisOperationsSessionRepository` is a `SessionRepository` that is implemented using Spring Data's `RedisOperations`.
In a web environment, this is typically used in combination with `SessionRepositoryFilter`.
The implementation supports `SessionDestroyedEvent` and `SessionCreatedEvent` through `SessionMessageListener`.

[[api-redisoperationssessionrepository-new]]
==== Instantiating a RedisOperationsSessionRepository

A typical example of how to create a new instance can be seen below:

[source,java,indent=0]
----
include::{indexdoc-tests}[tags=new-redisoperationssessionrepository]
----

For additional information on how to create a `RedisConnectionFactory`, refer to the Spring Data Redis Reference.

[[api-redisoperationssessionrepository-config]]
==== EnableRedisHttpSession

In a web environment, the simplest way to create a new `RedisOperationsSessionRepository` is to use `@EnableRedisHttpSession`.
Complete example usage can be found in the <<samples>>
You can use the following attributes to customize the configuration:

* **maxInactiveIntervalInSeconds** - the amount of time before the session will expire in seconds
* **redisNamespace** - allows configuring an application specific namespace for the sessions. Redis keys and channel ids will start with the prefix of `spring:session:<redisNamespace>:`.
* **redisFlushMode** - allows specifying when data will be written to Redis. The default is only when `save` is invoked on `SessionRepository`.
A value of `RedisFlushMode.IMMEDIATE` will write to Redis as soon as possible.

===== Custom RedisSerializer

You can customize the serialization by creating a Bean named `springSessionDefaultRedisSerializer` that implements `RedisSerializer<Object>`.

==== Redis TaskExecutor

`RedisOperationsSessionRepository` is subscribed to receive events from redis using a `RedisMessageListenerContainer`.
You can customize the way those events are dispatched, by creating a Bean named `springSessionRedisTaskExecutor` and/or a Bean `springSessionRedisSubscriptionExecutor`.
More details on configuring redis task executors can be found http://docs.spring.io/spring-data-redis/docs/current/reference/html/#redis:pubsub:subscribe:containers[here].

[[api-redisoperationssessionrepository-storage]]
==== Storage Details

The sections below outline how Redis is updated for each operation.
An example of creating a new session can be found below.
The subsequent sections describe the details.

----
HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe creationTime 1404360000000 \
	maxInactiveInterval 1800 \
	lastAccessedTime 1404360000000 \
	sessionAttr:attrName someAttrValue \
	sessionAttr2:attrName someAttrValue2
EXPIRE spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe 2100
APPEND spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe ""
EXPIRE spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe 1800
SADD spring:session:expirations:1439245080000 expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe
EXPIRE spring:session:expirations1439245080000 2100
----

===== Saving a Session

Each session is stored in Redis as a Hash.
Each session is set and updated using the HMSET command.
An example of how each session is stored can be seen below.

----
HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe creationTime 1404360000000 \
	maxInactiveInterval 1800 \
	lastAccessedTime 1404360000000 \
	sessionAttr:attrName someAttrValue \
	sessionAttr2:attrName someAttrValue2
----

In this example, the session following statements are true about the session:

* The session id is 33fdd1b6-b496-4b33-9f7d-df96679d32fe
* The session was created at 1404360000000 in milliseconds since midnight of 1/1/1970 GMT.
* The session expires in 1800 seconds (30 minutes).
* The session was last accessed at 1404360000000 in milliseconds since midnight of 1/1/1970 GMT.
* The session has two attributes.
The first is "attrName" with the value of "someAttrValue".
The second session attribute is named "attrName2" with the value of "someAttrValue2".

[[api-redisoperationssessionrepository-writes]]
===== Optimized Writes

The `Session` instances managed by `RedisOperationsSessionRepository` keeps track of the properties that have changed and only updates those.
This means if an attribute is written once and read many times we only need to write that attribute once.
For example, assume the session attribute "sessionAttr2" from earlier was updated.
The following would be executed upon saving:

----
HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe sessionAttr:attrName2 newValue
----

[[api-redisoperationssessionrepository-expiration]]
===== Session Expiration

An expiration is associated to each session using the EXPIRE command based upon the `ExpiringSession.getMaxInactiveInterval()`.
For example:

----
EXPIRE spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe 2100
----

You will note that the expiration that is set is 5 minutes after the session actually expires.
This is necessary so that the value of the session can be accessed when the session expires.
An expiration is set on the session itself five minutes after it actually expires to ensure it is cleaned up, but only after we perform any necessary processing.

[NOTE]
====
The `SessionRepository.getSession(String)` method ensures that no expired sessions will be returned.
This means there is no need to check the expiration before using a session.
====

Spring Session relies on the delete and expired http://redis.io/topics/notifications[keyspace notifications] from Redis to fire a <<api-redisoperationssessionrepository-sessiondestroyedevent,SessionDeletedEvent>> and <<api-redisoperationssessionrepository-sessiondestroyedevent,SessionExpiredEvent>> respectively.
It is the `SessionDeletedEvent` or `SessionExpiredEvent` that ensures resources associated with the Session are cleaned up.
For example, when using Spring Session's WebSocket support the Redis expired or delete event is what triggers any WebSocket connections associated with the session to be closed.

Expiration is not tracked directly on the session key itself since this would mean the session data would no longer be available. Instead a special session expires key is used. In our example the expires key is:

----
APPEND spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe ""
EXPIRE spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe 1800
----

When a session expires key is deleted or expires, the keyspace notification triggers a lookup of the actual session and a SessionDestroyedEvent is fired.

One problem with relying on Redis expiration exclusively is that Redis makes no guarantee of when the expired event will be fired if they key has not been accessed.
Specifically the background task that Redis uses to clean up expired keys is a low priority task and may not trigger the key expiration.
For additional details see http://redis.io/topics/notifications[Timing of expired events] section in the Redis documentation.

To circumvent the fact that expired events are not guaranteed to happen we can ensure that each key is accessed when it is expected to expire.
This means that if the TTL is expired on the key, Redis will remove the key and fire the expired event when we try to access they key.

For this reason, each session expiration is also tracked to the nearest minute.
This allows a background task to access the potentially expired sessions to ensure that Redis expired events are fired in a more deterministic fashion.
For example:

----
SADD spring:session:expirations:1439245080000 expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe
EXPIRE spring:session:expirations1439245080000 2100
----

The background task will then use these mappings to explicitly request each key.
By accessing they key, rather than deleting it, we ensure that Redis deletes the key for us only if the TTL is expired.

[NOTE]
====
We do not explicitly delete the keys since in some instances there may be a race condition that incorrectly identifies a key as expired when it is not.
Short of using distributed locks (which would kill our performance) there is no way to ensure the consistency of the expiration mapping.
By simply accessing the key, we ensure that the key is only removed if the TTL on that key is expired.
====

[[api-redisoperationssessionrepository-sessiondestroyedevent]]
==== SessionDeletedEvent and SessionExpiredEvent

`SessionDeletedEvent` and `SessionExpiredEvent` are both types of `SessionDestroyedEvent`.

`RedisOperationsSessionRepository` supports firing a `SessionDeletedEvent` whenever a `Session` is deleted or a `SessionExpiredEvent` when it expires.
This is necessary to ensure resources associated with the `Session` are properly cleaned up.

For example, when integrating with WebSockets the `SessionDestroyedEvent` is in charge of closing any active WebSocket connections.

Firing `SessionDeletedEvent` or `SessionExpiredEvent` is made available through the `SessionMessageListener` which listens to http://redis.io/topics/notifications[Redis Keyspace events].
In order for this to work, Redis Keyspace events for Generic commands and Expired events needs to be enabled.
For example:

[source,bash]
----
redis-cli config set notify-keyspace-events Egx
----

If you are using `@EnableRedisHttpSession` the `SessionMessageListener` and enabling the necessary Redis Keyspace events is done automatically.
However, in a secured Redis enviornment the config command is disabled.
This means that Spring Session cannot configure Redis Keyspace events for you.
To disable the automatic configuration add `ConfigureRedisAction.NO_OP` as a bean.

For example, Java Configuration can use the following:

[source,java,indent=0]
----
include::{docs-test-dir}docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java[tags=configure-redis-action]
----

XML Configuraiton can use the following:

[source,xml,indent=0]
----
include::{docs-test-resources-dir}docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests-context.xml[tags=configure-redis-action]
----

[[api-redisoperationssessionrepository-sessioncreatedevent]]
==== SessionCreatedEvent

When a session is created an event is sent to Redis with the channel of `spring:session:channel:created:33fdd1b6-b496-4b33-9f7d-df96679d32fe`
such that `33fdd1b6-b496-4b33-9f7d-df96679d32fe` is the session id. The body of the event will be the session that was created.

If registered as a MessageListener (default), then `RedisOperationsSessionRepository` will then translate the Redis message into a `SessionCreatedEvent`.

[[api-redisoperationssessionrepository-cli]]
==== Viewing the Session in Redis

After http://redis.io/topics/quickstart[installing redis-cli], you can inspect the values in Redis http://redis.io/commands#hash[using the redis-cli].
For example, enter the following into a terminal:

[source,bash]
----
$ redis-cli
redis 127.0.0.1:6379> keys *
1) "spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021" <1>
2) "spring:session:expirations:1418772300000" <2>
----

<1> The suffix of this key is the session identifier of the Spring Session.
<2> This key contains all the session ids that should be deleted at the time `1418772300000`.

You can also view the attributes of each session.

[source,bash]
----
redis 127.0.0.1:6379> hkeys spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021
1) "lastAccessedTime"
2) "creationTime"
3) "maxInactiveInterval"
4) "sessionAttr:username"
redis 127.0.0.1:6379> hget spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021 sessionAttr:username
"\xac\xed\x00\x05t\x00\x03rob"
----

[[api-gemfireoperationssessionrepository]]
=== GemFireOperationsSessionRepository

`GemFireOperationsSessionRepository` is a `SessionRepository` that is implemented using Spring Data's `GemFireOperationsSessionRepository`.
In a web environment, this is typically used in combination with `SessionRepositoryFilter`.
The implementation supports `SessionDestroyedEvent` and `SessionCreatedEvent` through `SessionMessageListener`.

[[api-gemfireoperationssessionrepository-indexing]]
==== Using Indexes with GemFire

While best practices concerning the proper definition of indexes that positively impact GemFire's performance is beyond
the scope of this document, it is important to realize that Spring Session Data GemFire creates and uses indexes to
query and find Sessions efficiently.

Out-of-the-box, Spring Session Data GemFire creates 1 Hash-typed Index on the principal name. There are two different buit in
strategies for finding the principal name. The first strategy is that the value of the session attribute with the name
`FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME` will be indexed to the same index name. For example:

[source,java,indent=0]
----
include::{docs-itest-dir}docs/http/HttpSessionGemFireIndexingITests.java[tags=findbyindexname-set]
include::{docs-itest-dir}docs/http/HttpSessionGemFireIndexingITests.java[tags=findbyindexname-get]
----

[[api-gemfireoperationssessionrepository-indexing-security]]
==== Using Indexes with GemFire & Spring Security

Alternatively, Spring Session Data GemFire will map Spring Security's current `Authentication#getName()` to the index
`FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME`. For example, if you are using Spring Security you can
find the current user's sessions using:

[source,java,indent=0]
----
include::{docs-itest-dir}docs/http/HttpSessionGemFireIndexingITests.java[tags=findbyspringsecurityindexname-context]
include::{docs-itest-dir}docs/http/HttpSessionGemFireIndexingITests.java[tags=findbyspringsecurityindexname-get]
----

[[api-gemfireoperationssessionrepository-indexing-custom]]
==== Using Custom Indexes with GemFire

This enables developers using the `GemFireOperationsSessionRepository` programmatically to query and find all Sessions
with a given principal name efficiently.

Additionally, Spring Session Data GemFire will create a Range-based Index on the implementing Session's Map-type
`attributes` property (i.e. on any arbitrary Session attribute) when a developer identifies 1 or more named Session
attributes that should be indexed by GemFire.

Sessions attributes to index can be specified with the `indexableSessionAttributes` attribute on the `@EnableGemFireHttpSession`
annotation.  A developer adds this annotation to their Spring application `@Configuration` class when s/he wishes to
enable Spring Session support for HttpSession backed by GemFire.

For example, the following configuration:

[source,java,indent=0]
----
include::{docs-itest-dir}docs/http/gemfire/indexablesessionattributes/GemFireHttpSessionConfig.java[tags=class-start]
	// ...
}
----

will allow searching for sessions using the following:

[source,java,indent=0]
----
include::{docs-itest-dir}docs/http/gemfire/indexablesessionattributes/HttpSessionGemFireIndexingCustomITests.java[tags=findbyindexname-set]
include::{docs-itest-dir}docs/http/gemfire/indexablesessionattributes/HttpSessionGemFireIndexingCustomITests.java[tags=findbyindexname-get]
----

NOTE: Only Session attribute names identified in the `@EnableGemFireHttpSession` annotation's `indexableSessionAttributes`
attribute will have an Index defined.  All other Session attributes will not be indexed.

However, there is one caveat. Any values stored in indexable Session attributes must implement the `java.lang.Comparable<T>`
interface. If those object values do not implement `Comparable`, then GemFire will throw an error on startup when the
Index is defined for Regions with persistent Session data, or when an attempt is made at runtime to assign the indexable
Session attribute a value that is not `Comparable` and the Session is saved to GemFire.

NOTE: Any Session attribute that is not indexed may store non-`Comparable` values.

To learn more about GemFire's Range-based Indexes, see http://gemfire.docs.pivotal.io/docs-gemfire/latest/developing/query_index/creating_map_indexes.html[Creating Indexes on Map Fields].

To learn more about GemFire Indexing in general, see http://gemfire.docs.pivotal.io/docs-gemfire/latest/developing/query_index/query_index.html[Working with Indexes].

[[api-mapsessionrepository]]
=== MapSessionRepository

The `MapSessionRepository` allows for persisting `ExpiringSession` in a `Map` with the key being the `ExpiringSession` id and the value being the `ExpiringSession`.
The implementation can be used with a `ConcurrentHashMap` as a testing or convenience mechanism.
Alternatively, it can be used with distributed `Map` implementations. For example, it can be used with Hazelcast.

[[api-mapsessionrepository-new]]
==== Instantiating MapSessionRepository

Creating a new instance is as simple as:

[source,java,indent=0]
----
include::{indexdoc-tests}[tags=new-mapsessionrepository]
----

[[api-mapsessionrepository-hazelcast]]
==== Using Spring Session and Hazlecast

The <<samples,Hazelcast Sample>> is a complete application demonstrating using Spring Session with Hazelcast.

To run it use the following:

	./gradlew :samples:hazelcast:tomcatRun

The <<samples,Hazelcast Spring Sample>> is a complete application demonstrating using Spring Session with Hazelcast and Spring Security.

It includes example Hazelcast `MapListener` implementations that support firing `SessionCreatedEvent`, `SessionDeletedEvent` and `SessionExpiredEvent`.

To run it use the following:

	./gradlew :samples:hazelcast-spring:tomcatRun

[[community]]
== Spring Session Community

We are glad to consider you a part of our community.
Please find additional information below.

[[community-support]]
=== Support

You can get help by asking questions on http://stackoverflow.com/questions/tagged/spring-session[StackOverflow with the tag spring-session].
Similarly we encourage helping others by answering questions on StackOverflow.

[[community-source]]
=== Source Code

Our source code can be found on github at https://github.com/spring-projects/spring-session/

[[community-issues]]
=== Issue Tracking

We track issues in github issues at https://github.com/spring-projects/spring-session/issues

[[community-contributing]]
=== Contributing

We appreciate https://help.github.com/articles/using-pull-requests/[Pull Requests].

[[community-license]]
=== License

Spring Session is Open Source software released under the http://www.apache.org/licenses/LICENSE-2.0.html[Apache 2.0 license].

[[minimum-requirements]]
== Minimum Requirements

The minimum requirements for Spring Session are:

* Java 5+
* If you are running in a Servlet Container (not required), Servlet 2.5+
* If you are using other Spring libraries (not required), the minimum required version is Spring 3.2.14.
While we re-run all unit tests against Spring 3.2.x, we recommend using the latest Spring 4.x version when possible.
* `@EnableRedisHttpSession` requires Redis 2.8+. This is necessary to support <<api-redisoperationssessionrepository-expiration,Session Expiration>>

[NOTE]
====
At its core Spring Session only has a required dependency on commons-logging.
For an example of using Spring Session without any other Spring dependencies, refer to the <<samples,hazelcast sample>> application.
====

= Spring Session
Rob Winch
:doctype: book
:indexdoc-tests: {docs-test-dir}docs/IndexDocTests.java
:websocketdoc-test-dir: {docs-test-dir}docs/websocket/
:toc: left

[[abstract]]

Spring Session provides an API and implementations for managing a user's session information.

[[introduction]]
== Introduction

Spring Session provides an API and implementations for managing a user's session information. It also provides transparent integration with:

* <<httpsession,HttpSession>> - allows replacing the HttpSession in an application container (i.e. Tomcat) neutral way.
Additional features include:
** **Clustered Sessions** - Spring Session makes it trivial to support <<httpsession-redis,clustered sessions>> without being tied to an application container specific solution.
** **Multiple Browser Sessions** - Spring Session supports <<httpsession-multi,managing multiple users' sessions>> in a single browser instance (i.e. multiple authenticated accounts similar to Google).
** **RESTful APIs** - Spring Session allows providing session ids in headers to work with <<httpsession-rest,RESTful APIs>>

* <<websocket,WebSocket>> - provides the ability to keep the `HttpSession` alive when receiving WebSocket messages

== What's New in 1.1

Below are the highlights of what is new in Spring Session 1.1. You can find a complete list of what's new in https://github.com/spring-projects/spring-session/issues?utf8=%E2%9C%93&q=milestone%3A%221.1.0+M1%22[1.1.0 M1] and https://github.com/spring-projects/spring-session/issues?utf8=%E2%9C%93&q=milestone%3A%221.1.0+RC1%22[1.1.0 RC1] by referring to the changelog.

* https://github.com/spring-projects/spring-session/issues/148[#148] - Added <<httpsession-gemfire,GemFire Support>>
* https://github.com/spring-projects/spring-session/issues/7[#7] - link:guides/findbyusername.html[Query by Username]
* https://github.com/spring-projects/spring-session/issues/299[#299] - link:guides/custom-cookie.html[Customize Cookie Creation]
* https://github.com/spring-projects/spring-session/issues/4[#4] - Add <<httpsession-httpsessionlistener,HttpSessionListener>> support
* https://github.com/spring-projects/spring-session/issues/283[#283] - Allow override default `RedisSerializer`
* https://github.com/spring-projects/spring-session/issues/277[#277] - Added link:guides/hazelcast-spring.html[@EnableHazelcastHttpSession]
* https://github.com/spring-projects/spring-session/issues/271[#271] - Performance improvements
* https://github.com/spring-projects/spring-session/pull/218[#218] - Allow scoping the session in Redis using <<api-redisoperationssessionrepository-config,redisNamespace>>
* https://github.com/spring-projects/spring-session/issues/273[#273] - Allow writing to Redis immediately (instead of lazily) using <<api-redisoperationssessionrepository-config,redisFlushMode>>
* https://github.com/spring-projects/spring-session/issues/272[#272] - Add `ExpiringSession.setLastAccessedTime(long)`
* https://github.com/spring-projects/spring-session/pull/349[#349] - Added https://gitter.im/spring-projects/spring-session[Gitter Room] for discussing Spring Session

[[samples]]
== Samples and Guides (Start Here)

If you are looking to get started with Spring Session, the best place to start is our Sample Applications.

.Sample Applications
|===
| Source | Description | Guide

| {gh-samples-url}httpsession[HttpSession]
| Demonstrates how to use Spring Session to replace the `HttpSession` with a Redis store.
| link:guides/httpsession.html[HttpSession Guide]

| {gh-samples-url}httpsession-xml[HttpSession XML]
| Demonstrates how to use Spring Session to replace the `HttpSession` with a Redis store using XML based configuration.
| link:guides/httpsession-xml.html[HttpSession XML Guide]

| {gh-samples-url}httpsession-gemfire-clientserver[HttpSession with GemFire (Client/Server)]
| Demonstrates how to use Spring Session to replace the `HttpSession` with GemFire using a Client/Server topology.
| link:guides/httpsession-gemfire-clientserver.html[HttpSession GemFire Client/Server Guide]

| {gh-samples-url}httpsession-gemfire-clientserver-xml[HttpSession with GemFire (Client/Server) using XML]
| Demonstrates how to use Spring Session to replace the `HttpSession` with GemFire using a Client/Server topology configured with XML.
| link:guides/httpsession-gemfire-clientserver-xml.html[HttpSession GemFire Client/Server XML Guide]

| {gh-samples-url}httpsession-gemfire-p2p[HttpSession with GemFire (P2P)]
| Demonstrates how to use Spring Session to replace the `HttpSession` with GemFire using a P2P topology.
| link:guides/httpsession-gemfire-p2p.html[HttpSession GemFire P2P Guide]

| {gh-samples-url}httpsession-gemfire-p2p-xml[HttpSession with GemFire (P2P) using XML]
| Demonstrates how to use Spring Session to replace the `HttpSession` with GemFire using a P2P topology configured with XML.
| link:guides/httpsession-gemfire-p2p-xml.html[HttpSession GemFire P2P XML Guide]

| {gh-samples-url}custom-cookie[Custom Cookie]
| Demonstrates how to use Spring Session and customize the cookie.
| link:guides/custom-cookie.html[Custom Cookie Guide]

| {gh-samples-url}boot[Spring Boot]
| Demonstrates how to use Spring Session with Spring Boot.
| link:guides/boot.html[Spring Boot Guide]

| {gh-samples-url}security[Spring Security]
| Demonstrates how to use Spring Session with an existing Spring Security application.
| link:guides/security.html[Spring Security Guide]

| {gh-samples-url}rest[REST]
| Demonstrates how to use Spring Session in a REST application to support authenticating with a header.
| link:guides/rest.html[REST Guide]

| {gh-samples-url}findbyusername[Find by Username]
| Demonstrates how to use Spring Session to find sessions by username.
| link:guides/findbyusername.html[Find by Username]

| {gh-samples-url}users[Multiple Users]
| Demonstrates how to use Spring Session to manage multiple simultaneous browser sessions (i.e Google Accounts).
| link:guides/users.html[Manage Multiple Users Guide]

| {gh-samples-url}websocket[WebSocket]
| Demonstrates how to use Spring Session with WebSockets.
| link:guides/websocket.html[WebSocket Guide]

[[samples-hazelcast]]
| {gh-samples-url}hazelcast[Hazelcast]
| Demonstrates how to use Spring Session with Hazelcast.
| TBD

[[samples-hazelcast-spring]]
| {gh-samples-url}hazelcast-spring[Hazelcast Spring]
| Demonstrates how to use Spring Session and Hazelcast with an existing Spring Security application.
| link:guides/hazelcast-spring.html[Hazelcast Spring Guide]

|===

[[httpsession]]
== HttpSession Integration

Spring Session provides transparent integration with `HttpSession`.
This means that developers can switch the `HttpSession` implementation out with an implementation that is backed by Spring Session.

[[httpsession-why]]
=== Why Spring Session & HttpSession?

We have already mentioned that Spring Session provides transparent integration with `HttpSession`, but what benefits do we get out of this?

* **Clustered Sessions** - Spring Session makes it trivial to support <<httpsession-redis,clustered sessions>> without being tied to an application container specific solution.
* **Multiple Browser Sessions** - Spring Session supports <<httpsession-multi,managing multiple users' sessions>> in a single browser instance (i.e. multiple authenticated accounts similar to Google).
* **RESTful APIs** - Spring Session allows providing session ids in headers to work with <<httpsession-rest,RESTful APIs>>

[[httpsession-redis]]
=== HttpSession with Redis

Using Spring Session with `HttpSession` is enabled by adding a Servlet Filter before anything that uses the `HttpSession`.
You can choose from enabling this using either:

* <<httpsession-redis-jc,Java Based Configuration>>
* <<httpsession-redis-xml,XML Based Configuration>>

[[httpsession-redis-jc]]
==== Redis Java Based Configuration

This section describes how to use Redis to back `HttpSession` using Java based configuration.

NOTE: The <<samples, HttpSession Sample>> provides a working sample on how to integrate Spring Session and `HttpSession` using XML configuration.
You can read the basic steps for integration below, but you are encouraged to follow along with the detailed HttpSession Guide when integrating with your own application.

include::guides/httpsession.adoc[tags=config,leveloffset=+3]

[[httpsession-redis-xml]]
==== Redis XML Based Configuration

This section describes how to use Redis to back `HttpSession` using XML based configuration.

NOTE: The <<samples, HttpSession XML Sample>> provides a working sample on how to integrate Spring Session and `HttpSession` using XML configuration.
You can read the basic steps for integration below, but you are encouraged to follow along with the detailed HttpSession XML Guide when integrating with your own application.

include::guides/httpsession-xml.adoc[tags=config,leveloffset=+3]

[[httpsession-gemfire]]
=== HttpSession with Pivotal GemFire

When https://pivotal.io/big-data/pivotal-gemfire[Pivotal GemFire] is used with Spring Session, a web application's
`HttpSession` can be replaced with a **clustered** implementation managed by GemFire and conveniently accessed
with Spring Session's API.

The two most common topologies to manage Spring Sessions using GemFire include:

* <<httpsession-gemfire-clientserver,Client-Server>>
* <<httpsession-gemfire-p2p,Peer-To-Peer (P2P)>>

Additionally, GemFire supports site-to-site replication using http://gemfire.docs.pivotal.io/docs-gemfire/topologies_and_comm/multi_site_configuration/chapter_overview.html[WAN functionality].
The ability to configure and use GemFire's WAN support is independent of Spring Session, and is beyond the scope
of this document. More details on GemFire WAN functionality can be found http://docs.spring.io/spring-data-gemfire/docs/current/reference/html/#bootstrap:gateway[here].

[[httpsession-gemfire-clientserver]]
==== GemFire Client-Server

The http://gemfire.docs.pivotal.io/docs-gemfire/latest/topologies_and_comm/cs_configuration/chapter_overview.html[Client-Server]
topology will probably be the more common configuration preference for users when using GemFire as a provider in
Spring Session since a GemFire server will have significantly different and unique JVM heap requirements when compared
to the application. Using a client-server topology enables an application to manage (e.g. replicate) application state
independently from other application processes.

In a client-server topology, an application using Spring Session will open a client cache connection to a (remote)
GemFire server cluster to manage and provide consistent access to all `HttpSession` state.

You can configure a Client-Server topology with either:

* <<httpsession-gemfire-clientserver-java,Java-based Configuration>>
* <<httpsession-gemfire-clientserver-xml,XML-based Configuration>>

[[httpsession-gemfire-clientserver-java]]
===== GemFire Client-Server Java-based Configuration

This section describes how to use GemFire's Client-Server topology to back an `HttpSession` with Java-based configuration.

NOTE: The <<samples,HttpSession with GemFire (Client-Server) Sample>> provides a working sample on how to integrate
Spring Session and GemFire to replace the HttpSession using Java configuration. You can read the basic steps for
integration below, but you are encouraged to follow along with the detailed HttpSession with GemFire (Client-Server)
Guide when integrating with your own application.

include::guides/httpsession-gemfire-clientserver.adoc[tags=config,leveloffset=+3]

[[http-session-gemfire-clientserver-xml]]
===== GemFire Client-Server XML-based Configuration

This section describes how to use GemFire's Client-Server topology to back an `HttpSession` with XML-based configuration.

NOTE: The <<samples,HttpSession with GemFire (Client-Server) using XML Sample>> provides a working sample on how to
integrate Spring Session and GemFire to replace the `HttpSession` using XML configuration. You can read the basic steps
for integration below, but you are encouraged to follow along with the detailed HttpSession with GemFire (Client-Server)
using XML Guide when integrating with your own application.

include::guides/httpsession-gemfire-clientserver-xml.adoc[tags=config,leveloffset=+3]

[[httpsession-gemfire-p2p]]
==== GemFire Peer-To-Peer (P2P)

Perhaps less common would be to configure the Spring Session application as a peer member in the GemFire cluster using
the http://gemfire.docs.pivotal.io/docs-gemfire/latest/topologies_and_comm/p2p_configuration/chapter_overview.html[Peer-To-Peer (P2P)] topology.
In this configuration, a Spring Session application would be an actual data node (server) in the GemFire cluster,
and **not** a cache client as before.

One advantage to this approach is the proximity of the application to the application's state (i.e. it's data). However,
there are other effective means of accomplishing similar data dependent computations, such as using GemFire's
http://gemfire.docs.pivotal.io/docs-gemfire/latest/developing/function_exec/chapter_overview.html[Function Execution].
Any of GemFire's other http://gemfire.docs.pivotal.io/docs-gemfire/latest/getting_started/product_intro.html[features]
can be used when GemFire is serving as a provider in Spring Session.

P2P is very useful for both testing purposes as well as smaller, more focused and self-contained applications,
such as those found in a microservices architecture, and will most certainly improve on your application's latency,
throughput and consistency needs.

You can configure a Peer-To-Peer (P2P) topology with either:

* <<httpsession-gemfire-p2p-java,Java-based Configuration>>
* <<httpsession-gemfire-p2p-xml,XML-based Configuration>>

[[httpsession-gemfire-p2p-java]]
===== GemFire Peer-To-Peer (P2P) Java-based Configuration

This section describes how to use GemFire's Peer-To-Peer (P2P) topology to back an `HttpSession` using Java-based configuration.

NOTE: The <<samples, HttpSession with GemFire (P2P) Sample>> provides a working sample on how to integrate
Spring Session and GemFire to replace the `HttpSession` using Java configuration. You can read the basic steps
for integration below, but you are encouraged to follow along with the detailed HttpSession with GemFire (P2P) Guide
when integrating with your own application.

include::guides/httpsession-gemfire-p2p.adoc[tags=config,leveloffset=+3]

[[httpsession-gemfire-p2p-xml]]
===== GemFire Peer-To-Peer (P2P) XML-based Configuration

This section describes how to use GemFire's Peer-To-Peer (P2P) topology to back an `HttpSession` using XML-based configuration.

NOTE: The <<samples, HttpSession with GemFire (P2P) using XML Sample>> provides a working sample on how to integrate
Spring Session and GemFire to replace the `HttpSession` using XML configuration. You can read the basic steps for
integration below, but you are encouraged to follow along with the detailed HttpSession with GemFire (P2P) using XML
Guide when integrating with your own application.

include::guides/httpsession-gemfire-p2p-xml.adoc[tags=config,leveloffset=+3]

[[httpsession-how]]
=== How HttpSession Integration Works

Fortunately both `HttpSession` and `HttpServletRequest` (the API for obtaining an `HttpSession`) are both interfaces.
This means that we can provide our own implementations for each of these APIs.

NOTE: This section describes how Spring Session provides transparent integration with `HttpSession`. The intent is so that user's can understand what is happening under the covers. This functionality is already integrated and you do NOT need to implement this logic yourself.

First we create a custom `HttpServletRequest` that returns a custom implementation of `HttpSession`.
It looks something like the following:

[source, java]
----
public class SessionRepositoryRequestWrapper extends HttpServletRequestWrapper {

	public SessionRepositoryRequestWrapper(HttpServletRequest original) {
		super(original);
	}

	public HttpSession getSession() {
		return getSession(true);
	}

	public HttpSession getSession(boolean createNew) {
		// create an HttpSession implementation from Spring Session
	}

	// ... other methods delegate to the original HttpServletRequest ...
}
----

Any method that returns an `HttpSession` is overridden.
All other methods are implemented by `HttpServletRequestWrapper` and simply delegate to the original `HttpServletRequest` implementation.

We replace the `HttpServletRequest` implementation using a servlet `Filter` called `SessionRepositoryFilter`.
The pseudocode can be found below:

[source, java]
----
public class SessionRepositoryFilter implements Filter {

	public doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		SessionRepositoryRequestWrapper customRequest =
			new SessionRepositoryRequestWrapper(httpRequest);

		chain.doFilter(customRequest, response, chain);
	}

	// ...
}
----

By passing in a custom `HttpServletRequest` implementation into the `FilterChain` we ensure that anything invoked after our `Filter` uses the custom `HttpSession` implementation.
This highlights why it is important that Spring Session's `SessionRepositoryFilter` must be placed before anything that interacts with the `HttpSession`.

[[httpsession-multi]]
=== Multiple HttpSessions in Single Browser

Spring Session has the ability to support multiple sessions in a single browser instance.
This provides the ability to support authenticating with multiple users in the same browser instance (i.e. Google Accounts).

NOTE: The <<samples,Manage Multiple Users Guide>> provides a complete working example of managing multiple users in the same browser instance.
You can follow the basic steps for integration below, but you are encouraged to follow along with the detailed Manage Multiple Users Guide when integrating with your own application.

include::guides/users.adoc[tags=how-does-it-work,leveloffset=+1]

[[httpsession-rest]]
=== HttpSession & RESTful APIs

Spring Session can work with RESTful APIs by allowing the session to be provided in a header.

NOTE: The <<samples, REST Sample>> provides a working sample on how to use Spring Session in a REST application to support authenticating with a header.
You can follow the basic steps for integration below, but you are encouraged to follow along with the detailed REST Guide when integrating with your own application.

include::guides/rest.adoc[tags=config,leveloffset=+2]

[[httpsession-httpsessionlistener]]
=== HttpSessionListener

Spring Session supports `HttpSessionListener` by translating `SessionDestroyedEvent` and `SessionCreatedEvent` into `HttpSessionEvent` by declaring `SessionEventHttpSessionListenerAdapter`.
To use this support, you need to:

* Ensure your `SessionRepository` implementation supports and is configured to fire `SessionDestroyedEvent` and `SessionCreatedEvent`.
* Configure `SessionEventHttpSessionListenerAdapter` as a Spring bean.
* Inject every `HttpSessionListener` into the `SessionEventHttpSessionListenerAdapter`

If you are using the configuration support documented in <<httpsession-redis,HttpSession with Redis>>, then all you need to do is register every `HttpSessionListener` as a bean.
For example, assume you want to support Spring Security's concurrency control and need to use `HttpSessionEventPublisher` you can simply add `HttpSessionEventPublisher` as a bean.
In Java configuration, this might look like:

[source,java,indent=0]
----
include::{docs-test-dir}docs/http/RedisHttpSessionConfig.java[tags=config]
----

In XML configuration, this might look like:

[source,xml,indent=0]
----
include::{docs-test-resources-dir}docs/http/HttpSessionListenerXmlTests-context.xml[tags=config]
----

[[websocket]]
== WebSocket Integration

Spring Session provides transparent integration with Spring's WebSocket support.

include::guides/websocket.adoc[tags=disclaimer,leveloffset=+1]

[[websocket-why]]
=== Why Spring Session & WebSockets?

So why do we need Spring Session when using WebSockets?

Consider an email application that does much of its work through HTTP requests.
However, there is also a chat application embedded within it that works over WebSocket APIs.
If a user is actively chatting with someone, we should not timeout the `HttpSession` since this would be pretty poor user experience.
However, this is exactly what https://java.net/jira/browse/WEBSOCKET_SPEC-175[JSR-356] does.

Another issue is that according to JSR-356 if the `HttpSession` times out any WebSocket that was created with that HttpSession and an authenticated user should be forcibly closed.
This means that if we are actively chatting in our application and are not using the HttpSession, then we will also disconnect from our conversation!

[[websocket-usage]]
=== WebSocket Usage

The <<samples, WebSocket Sample>> provides a working sample on how to integrate Spring Session with WebSockets.
You can follow the basic steps for integration below, but you are encouraged to follow along with the detailed WebSocket Guide when integrating with your own application:

[[websocket-httpsession]]
==== HttpSession Integration

Before using WebSocket integration, you should be sure that you have <<httpsession>> working first.

include::guides/websocket.adoc[tags=config,leveloffset=+2]

[[api]]
== API Documentation

You can browse the complete link:../../api/[Javadoc] online. The key APIs are described below:

[[api-session]]
=== Session

A `Session` is a simplified `Map` of name value pairs.

Typical usage might look like the following:

[source,java,indent=0]
----
include::{indexdoc-tests}[tags=repository-demo]
----

<1> We create a `SessionRepository` instance with a generic type, `S`, that extends `Session`. The generic type is defined in our class.
<2> We create a new `Session` using our `SessionRepository` and assign it to a variable of type `S`.
<3> We interact with the `Session`. In our example, we demonstrate saving a `User` to the `Session`.
<4> We now save the `Session`. This is why we needed the generic type `S`. The `SessionRepository` only allows saving `Session` instances that were created or retrieved using the same `SessionRepository`. This allows for the `SessionRepository` to make implementation specific optimizations (i.e. only writing attributes that have changed).
<5> We retrieve the `Session` from the `SessionRepository`.
<6> We obtain the persisted `User` from our `Session` without the need for explicitly casting our attribute.

[[api-expiringsession]]
=== ExpiringSession

An `ExpiringSession` extends a `Session` by providing attributes related to the `Session` instance's expiration.
If there is no need to interact with the expiration information, prefer using the more simple `Session` API.

Typical usage might look like the following:

[source,java,indent=0]
----
include::{indexdoc-tests}[tags=expire-repository-demo]
----

<1> We create a `SessionRepository` instance with a generic type, `S`, that extends `ExpiringSession`. The generic type is defined in our class.
<2> We create a new `ExpiringSession` using our `SessionRepository` and assign it to a variable of type `S`.
<3> We interact with the `ExpiringSession`.
In our example, we demonstrate updating the amount of time the `ExpiringSession` can be inactive before it expires.
<4> We now save the `ExpiringSession`.
This is why we needed the generic type `S`.
The `SessionRepository` only allows saving `ExpiringSession` instances that were created or retrieved using the same `SessionRepository`.
This allows for the `SessionRepository` to make implementation specific optimizations (i.e. only writing attributes that have changed).
The last accessed time is automatically updated when the `ExpiringSession` is saved.
<5> We retrieve the `ExpiringSession` from the `SessionRepository`.
If the `ExpiringSession` were expired, the result would be null.

[[api-sessionrepository]]
=== SessionRepository

A `SessionRepository` is in charge of creating, retrieving, and persisting `Session` instances.

If possible, developers should not interact directly with a `SessionRepository` or a `Session`.
Instead, developers should prefer interacting with `SessionRepository` and `Session` indirectly through the <<httpsession,HttpSession>> and <<websocket,WebSocket>> integration.

[[api-findbyindexnamesessionrepository]]
=== FindByIndexNameSessionRepository

Spring Session's most basic API for using a `Session` is the `SessionRepository`.
This API is intentionally very simple, so that it is easy to provide additional implementations with basic functionality.

Some `SessionRepository` implementations may choose to implement `FindByIndexNameSessionRepository` also.
For example, Spring's Redis support implements `FindByIndexNameSessionRepository`.

The `FindByIndexNameSessionRepository` adds a single method to look up all the sessions for a particular user.
This is done by ensuring that the session attribute with the name `FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME` is populated with the username.
It is the responsibility of the developer to ensure the attribute is populated since Spring Session is not aware of the authentication mechanism being used.
An example of how this might be used can be seen below:

[source,java,indent=0]
----
include::{docs-test-dir}docs/FindByIndexNameSessionRepositoryTests.java[tags=set-username]
----

[NOTE]
====
Some implementations of `FindByIndexNameSessionRepository` will provide hooks to automatically index other session attributes.
For example, many implementations will automatically ensure the current Spring Security user name is indexed with the index name `FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME`.
====

Once the session is indexed, it can be found using the following:

[source,java,indent=0]
----
include::{docs-test-dir}docs/FindByIndexNameSessionRepositoryTests.java[tags=findby-username]
----

[[api-enablespringhttpsession]]
=== EnableSpringHttpSession

The `@EnableSpringHttpSession` annotation can be added to an `@Configuration` class to expose the `SessionRepositoryFilter` as a bean named "springSessionRepositoryFilter".
In order to leverage the annotation, a single `SessionRepository` bean must be provided.
For example:

[source,java,indent=0]
----
include::{docs-test-dir}docs/SpringHttpSessionConfig.java[tags=class]
----

It is important to note that no infrastructure for session expirations is configured for you out of the box.
This is because things like session expiration are highly implementation dependent.
This means if you require cleaning up expired sessions, you are responsible for cleaning up the expired sessions.

[[api-enablehazelcasthttpsession]]
=== EnableHazelcastHttpSession

If you wish to use http://hazelcast.org/[Hazelcast] as your backing source for the `SessionRepository`, then the `@EnableHazelcastHttpSession` annotation
can be added to an `@Configuration` class. This extends the functionality provided by the `@EnableSpringHttpSession` annotation but makes the `SessionRepository` for you in Hazelcast.
You must provide a single `HazelcastInstance` bean for the configuration to work.
For example:

[source,java,indent=0]
----
include::{docs-test-dir}docs/http/HazelcastHttpSessionConfig.java[tags=config]
----

This will configure Hazelcast in embedded mode with default configuration.
See the http://docs.hazelcast.org/docs/latest/manual/html-single/index.html#hazelcast-configuration[Hazelcast documentation] for
detailed information on configuration options for Hazelcast.

[[api-enablehazelcasthttpsession-storage]]
==== Storage Details

Sessions will be stored in a distributed `Map` in Hazelcast using a <<api-mapsessionrepository,MapSessionRepository>>.
The `Map` interface methods will be used to `get()` and `put()` Sessions.
The expiration of a session in the `Map` is handled by Hazelcast's support for setting the time to live on an entry when it is `put()` into the `Map`. Entries (sessions) that have been idle longer than the time to live will be automatically removed from the `Map`.

You shouldn't need to configure any settings such as `max-idle-seconds` or `time-to-live-seconds` for the `Map` within the Hazelcast configuration.

[[api-enablehazelcasthttpsession-customize]]
==== Basic Customization
You can use the following attributes on `@EnableHazelcastHttpSession` to customize the configuration:

* **maxInactiveIntervalInSeconds** - the amount of time before the session will expire in seconds. Default is 1800 seconds (30 minutes)
* **sessionMapName** - the name of the distributed `Map` that will be used in Hazelcast to store the session data.

[[api-enablehazelcasthttpsession-events]]
==== Session Events
Using a `MapListener` to respond to entries being added, evicted, and removed from the distributed `Map`, these events will trigger
publishing SessionCreatedEvent, SessionExpiredEvent, and SessionDeletedEvent events respectively using the `ApplicationEventPublisher`.

[[api-redisoperationssessionrepository]]
=== RedisOperationsSessionRepository

`RedisOperationsSessionRepository` is a `SessionRepository` that is implemented using Spring Data's `RedisOperations`.
In a web environment, this is typically used in combination with `SessionRepositoryFilter`.
The implementation supports `SessionDestroyedEvent` and `SessionCreatedEvent` through `SessionMessageListener`.

[[api-redisoperationssessionrepository-new]]
==== Instantiating a RedisOperationsSessionRepository

A typical example of how to create a new instance can be seen below:

[source,java,indent=0]
----
include::{indexdoc-tests}[tags=new-redisoperationssessionrepository]
----

For additional information on how to create a `RedisConnectionFactory`, refer to the Spring Data Redis Reference.

[[api-redisoperationssessionrepository-config]]
==== EnableRedisHttpSession

In a web environment, the simplest way to create a new `RedisOperationsSessionRepository` is to use `@EnableRedisHttpSession`.
Complete example usage can be found in the <<samples>>
You can use the following attributes to customize the configuration:

* **maxInactiveIntervalInSeconds** - the amount of time before the session will expire in seconds
* **redisNamespace** - allows configuring an application specific namespace for the sessions. Redis keys and channel ids will start with the prefix of `spring:session:<redisNamespace>:`.
* **redisFlushMode** - allows specifying when data will be written to Redis. The default is only when `save` is invoked on `SessionRepository`.
A value of `RedisFlushMode.IMMEDIATE` will write to Redis as soon as possible.

===== Custom RedisSerializer

You can customize the serialization by creating a Bean named `springSessionDefaultRedisSerializer` that implements `RedisSerializer<Object>`.

==== Redis TaskExecutor

`RedisOperationsSessionRepository` is subscribed to receive events from redis using a `RedisMessageListenerContainer`.
You can customize the way those events are dispatched, by creating a Bean named `springSessionRedisTaskExecutor` and/or a Bean `springSessionRedisSubscriptionExecutor`.
More details on configuring redis task executors can be found http://docs.spring.io/spring-data-redis/docs/current/reference/html/#redis:pubsub:subscribe:containers[here].

[[api-redisoperationssessionrepository-storage]]
==== Storage Details

The sections below outline how Redis is updated for each operation.
An example of creating a new session can be found below.
The subsequent sections describe the details.

----
HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe creationTime 1404360000000 \
	maxInactiveInterval 1800 \
	lastAccessedTime 1404360000000 \
	sessionAttr:attrName someAttrValue \
	sessionAttr2:attrName someAttrValue2
EXPIRE spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe 2100
APPEND spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe ""
EXPIRE spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe 1800
SADD spring:session:expirations:1439245080000 expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe
EXPIRE spring:session:expirations1439245080000 2100
----

===== Saving a Session

Each session is stored in Redis as a Hash.
Each session is set and updated using the HMSET command.
An example of how each session is stored can be seen below.

----
HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe creationTime 1404360000000 \
	maxInactiveInterval 1800 \
	lastAccessedTime 1404360000000 \
	sessionAttr:attrName someAttrValue \
	sessionAttr2:attrName someAttrValue2
----

In this example, the session following statements are true about the session:

* The session id is 33fdd1b6-b496-4b33-9f7d-df96679d32fe
* The session was created at 1404360000000 in milliseconds since midnight of 1/1/1970 GMT.
* The session expires in 1800 seconds (30 minutes).
* The session was last accessed at 1404360000000 in milliseconds since midnight of 1/1/1970 GMT.
* The session has two attributes.
The first is "attrName" with the value of "someAttrValue".
The second session attribute is named "attrName2" with the value of "someAttrValue2".

[[api-redisoperationssessionrepository-writes]]
===== Optimized Writes

The `Session` instances managed by `RedisOperationsSessionRepository` keeps track of the properties that have changed and only updates those.
This means if an attribute is written once and read many times we only need to write that attribute once.
For example, assume the session attribute "sessionAttr2" from earlier was updated.
The following would be executed upon saving:

----
HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe sessionAttr:attrName2 newValue
----

[[api-redisoperationssessionrepository-expiration]]
===== Session Expiration

An expiration is associated to each session using the EXPIRE command based upon the `ExpiringSession.getMaxInactiveInterval()`.
For example:

----
EXPIRE spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe 2100
----

You will note that the expiration that is set is 5 minutes after the session actually expires.
This is necessary so that the value of the session can be accessed when the session expires.
An expiration is set on the session itself five minutes after it actually expires to ensure it is cleaned up, but only after we perform any necessary processing.

[NOTE]
====
The `SessionRepository.getSession(String)` method ensures that no expired sessions will be returned.
This means there is no need to check the expiration before using a session.
====

Spring Session relies on the delete and expired http://redis.io/topics/notifications[keyspace notifications] from Redis to fire a <<api-redisoperationssessionrepository-sessiondestroyedevent,SessionDeletedEvent>> and <<api-redisoperationssessionrepository-sessiondestroyedevent,SessionExpiredEvent>> respectively.
It is the `SessionDeletedEvent` or `SessionExpiredEvent` that ensures resources associated with the Session are cleaned up.
For example, when using Spring Session's WebSocket support the Redis expired or delete event is what triggers any WebSocket connections associated with the session to be closed.

Expiration is not tracked directly on the session key itself since this would mean the session data would no longer be available. Instead a special session expires key is used. In our example the expires key is:

----
APPEND spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe ""
EXPIRE spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe 1800
----

When a session expires key is deleted or expires, the keyspace notification triggers a lookup of the actual session and a SessionDestroyedEvent is fired.

One problem with relying on Redis expiration exclusively is that Redis makes no guarantee of when the expired event will be fired if they key has not been accessed.
Specifically the background task that Redis uses to clean up expired keys is a low priority task and may not trigger the key expiration.
For additional details see http://redis.io/topics/notifications[Timing of expired events] section in the Redis documentation.

To circumvent the fact that expired events are not guaranteed to happen we can ensure that each key is accessed when it is expected to expire.
This means that if the TTL is expired on the key, Redis will remove the key and fire the expired event when we try to access they key.

For this reason, each session expiration is also tracked to the nearest minute.
This allows a background task to access the potentially expired sessions to ensure that Redis expired events are fired in a more deterministic fashion.
For example:

----
SADD spring:session:expirations:1439245080000 expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe
EXPIRE spring:session:expirations1439245080000 2100
----

The background task will then use these mappings to explicitly request each key.
By accessing they key, rather than deleting it, we ensure that Redis deletes the key for us only if the TTL is expired.

[NOTE]
====
We do not explicitly delete the keys since in some instances there may be a race condition that incorrectly identifies a key as expired when it is not.
Short of using distributed locks (which would kill our performance) there is no way to ensure the consistency of the expiration mapping.
By simply accessing the key, we ensure that the key is only removed if the TTL on that key is expired.
====

[[api-redisoperationssessionrepository-sessiondestroyedevent]]
==== SessionDeletedEvent and SessionExpiredEvent

`SessionDeletedEvent` and `SessionExpiredEvent` are both types of `SessionDestroyedEvent`.

`RedisOperationsSessionRepository` supports firing a `SessionDeletedEvent` whenever a `Session` is deleted or a `SessionExpiredEvent` when it expires.
This is necessary to ensure resources associated with the `Session` are properly cleaned up.

For example, when integrating with WebSockets the `SessionDestroyedEvent` is in charge of closing any active WebSocket connections.

Firing `SessionDeletedEvent` or `SessionExpiredEvent` is made available through the `SessionMessageListener` which listens to http://redis.io/topics/notifications[Redis Keyspace events].
In order for this to work, Redis Keyspace events for Generic commands and Expired events needs to be enabled.
For example:

[source,bash]
----
redis-cli config set notify-keyspace-events Egx
----

If you are using `@EnableRedisHttpSession` the `SessionMessageListener` and enabling the necessary Redis Keyspace events is done automatically.
However, in a secured Redis enviornment the config command is disabled.
This means that Spring Session cannot configure Redis Keyspace events for you.
To disable the automatic configuration add `ConfigureRedisAction.NO_OP` as a bean.

For example, Java Configuration can use the following:

[source,java,indent=0]
----
include::{docs-test-dir}docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java[tags=configure-redis-action]
----

XML Configuraiton can use the following:

[source,xml,indent=0]
----
include::{docs-test-resources-dir}docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests-context.xml[tags=configure-redis-action]
----

[[api-redisoperationssessionrepository-sessioncreatedevent]]
==== SessionCreatedEvent

When a session is created an event is sent to Redis with the channel of `spring:session:channel:created:33fdd1b6-b496-4b33-9f7d-df96679d32fe`
such that `33fdd1b6-b496-4b33-9f7d-df96679d32fe` is the session id. The body of the event will be the session that was created.

If registered as a MessageListener (default), then `RedisOperationsSessionRepository` will then translate the Redis message into a `SessionCreatedEvent`.

[[api-redisoperationssessionrepository-cli]]
==== Viewing the Session in Redis

After http://redis.io/topics/quickstart[installing redis-cli], you can inspect the values in Redis http://redis.io/commands#hash[using the redis-cli].
For example, enter the following into a terminal:

[source,bash]
----
$ redis-cli
redis 127.0.0.1:6379> keys *
1) "spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021" <1>
2) "spring:session:expirations:1418772300000" <2>
----

<1> The suffix of this key is the session identifier of the Spring Session.
<2> This key contains all the session ids that should be deleted at the time `1418772300000`.

You can also view the attributes of each session.

[source,bash]
----
redis 127.0.0.1:6379> hkeys spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021
1) "lastAccessedTime"
2) "creationTime"
3) "maxInactiveInterval"
4) "sessionAttr:username"
redis 127.0.0.1:6379> hget spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021 sessionAttr:username
"\xac\xed\x00\x05t\x00\x03rob"
----

[[api-gemfireoperationssessionrepository]]
=== GemFireOperationsSessionRepository

`GemFireOperationsSessionRepository` is a `SessionRepository` that is implemented using Spring Data's `GemFireOperationsSessionRepository`.
In a web environment, this is typically used in combination with `SessionRepositoryFilter`.
The implementation supports `SessionDestroyedEvent` and `SessionCreatedEvent` through `SessionMessageListener`.

[[api-gemfireoperationssessionrepository-indexing]]
==== Using Indexes with GemFire

While best practices concerning the proper definition of indexes that positively impact GemFire's performance is beyond
the scope of this document, it is important to realize that Spring Session Data GemFire creates and uses indexes to
query and find Sessions efficiently.

Out-of-the-box, Spring Session Data GemFire creates 1 Hash-typed Index on the principal name. There are two different buit in
strategies for finding the principal name. The first strategy is that the value of the session attribute with the name
`FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME` will be indexed to the same index name. For example:

[source,java,indent=0]
----
include::{docs-itest-dir}docs/http/HttpSessionGemFireIndexingITests.java[tags=findbyindexname-set]
include::{docs-itest-dir}docs/http/HttpSessionGemFireIndexingITests.java[tags=findbyindexname-get]
----

[[api-gemfireoperationssessionrepository-indexing-security]]
==== Using Indexes with GemFire & Spring Security

Alternatively, Spring Session Data GemFire will map Spring Security's current `Authentication#getName()` to the index
`FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME`. For example, if you are using Spring Security you can
find the current user's sessions using:

[source,java,indent=0]
----
include::{docs-itest-dir}docs/http/HttpSessionGemFireIndexingITests.java[tags=findbyspringsecurityindexname-context]
include::{docs-itest-dir}docs/http/HttpSessionGemFireIndexingITests.java[tags=findbyspringsecurityindexname-get]
----

[[api-gemfireoperationssessionrepository-indexing-custom]]
==== Using Custom Indexes with GemFire

This enables developers using the `GemFireOperationsSessionRepository` programmatically to query and find all Sessions
with a given principal name efficiently.

Additionally, Spring Session Data GemFire will create a Range-based Index on the implementing Session's Map-type
`attributes` property (i.e. on any arbitrary Session attribute) when a developer identifies 1 or more named Session
attributes that should be indexed by GemFire.

Sessions attributes to index can be specified with the `indexableSessionAttributes` attribute on the `@EnableGemFireHttpSession`
annotation.  A developer adds this annotation to their Spring application `@Configuration` class when s/he wishes to
enable Spring Session support for HttpSession backed by GemFire.

For example, the following configuration:

[source,java,indent=0]
----
include::{docs-itest-dir}docs/http/gemfire/indexablesessionattributes/GemFireHttpSessionConfig.java[tags=class-start]
	// ...
}
----

will allow searching for sessions using the following:

[source,java,indent=0]
----
include::{docs-itest-dir}docs/http/gemfire/indexablesessionattributes/HttpSessionGemFireIndexingCustomITests.java[tags=findbyindexname-set]
include::{docs-itest-dir}docs/http/gemfire/indexablesessionattributes/HttpSessionGemFireIndexingCustomITests.java[tags=findbyindexname-get]
----

NOTE: Only Session attribute names identified in the `@EnableGemFireHttpSession` annotation's `indexableSessionAttributes`
attribute will have an Index defined.  All other Session attributes will not be indexed.

However, there is one caveat. Any values stored in indexable Session attributes must implement the `java.lang.Comparable<T>`
interface. If those object values do not implement `Comparable`, then GemFire will throw an error on startup when the
Index is defined for Regions with persistent Session data, or when an attempt is made at runtime to assign the indexable
Session attribute a value that is not `Comparable` and the Session is saved to GemFire.

NOTE: Any Session attribute that is not indexed may store non-`Comparable` values.

To learn more about GemFire's Range-based Indexes, see http://gemfire.docs.pivotal.io/docs-gemfire/latest/developing/query_index/creating_map_indexes.html[Creating Indexes on Map Fields].

To learn more about GemFire Indexing in general, see http://gemfire.docs.pivotal.io/docs-gemfire/latest/developing/query_index/query_index.html[Working with Indexes].

[[api-mapsessionrepository]]
=== MapSessionRepository

The `MapSessionRepository` allows for persisting `ExpiringSession` in a `Map` with the key being the `ExpiringSession` id and the value being the `ExpiringSession`.
The implementation can be used with a `ConcurrentHashMap` as a testing or convenience mechanism.
Alternatively, it can be used with distributed `Map` implementations. For example, it can be used with Hazelcast.

[[api-mapsessionrepository-new]]
==== Instantiating MapSessionRepository

Creating a new instance is as simple as:

[source,java,indent=0]
----
include::{indexdoc-tests}[tags=new-mapsessionrepository]
----

[[api-mapsessionrepository-hazelcast]]
==== Using Spring Session and Hazlecast

The <<samples,Hazelcast Sample>> is a complete application demonstrating using Spring Session with Hazelcast.

To run it use the following:

	./gradlew :samples:hazelcast:tomcatRun

The <<samples,Hazelcast Spring Sample>> is a complete application demonstrating using Spring Session with Hazelcast and Spring Security.

It includes example Hazelcast `MapListener` implementations that support firing `SessionCreatedEvent`, `SessionDeletedEvent` and `SessionExpiredEvent`.

To run it use the following:

	./gradlew :samples:hazelcast-spring:tomcatRun

[[api-mapsessionrepository-hazelcast]]
==== Using Spring Session and Hazlecast

[[community]]
== Spring Session Community

We are glad to consider you a part of our community.
Please find additional information below.

[[community-support]]
=== Support

You can get help by asking questions on http://stackoverflow.com/questions/tagged/spring-session[StackOverflow with the tag spring-session].
Similarly we encourage helping others by answering questions on StackOverflow.

[[community-source]]
=== Source Code

Our source code can be found on github at https://github.com/spring-projects/spring-session/

[[community-issues]]
=== Issue Tracking

We track issues in github issues at https://github.com/spring-projects/spring-session/issues

[[community-contributing]]
=== Contributing

We appreciate https://help.github.com/articles/using-pull-requests/[Pull Requests].

[[community-license]]
=== License

Spring Session is Open Source software released under the http://www.apache.org/licenses/LICENSE-2.0.html[Apache 2.0 license].

[[minimum-requirements]]
== Minimum Requirements

The minimum requirements for Spring Session are:

* Java 5+
* If you are running in a Servlet Container (not required), Servlet 2.5+
* If you are using other Spring libraries (not required), the minimum required version is Spring 3.2.14.
While we re-run all unit tests against Spring 3.2.x, we recommend using the latest Spring 4.x version when possible.
* `@EnableRedisHttpSession` requires Redis 2.8+. This is necessary to support <<api-redisoperationssessionrepository-expiration,Session Expiration>>

[NOTE]
====
At its core Spring Session only has a required dependency on commons-logging.
For an example of using Spring Session without any other Spring dependencies, refer to the <<samples,hazelcast sample>> application.
====


Update 2016-12-12-Heroku-Memo-for-postresql.adoc