This guide describes how to configure Pivotal GemFire as a provider in Spring Session to transparently back a web application’s HttpSession using Java Configuration.

The completed guide can be found in the HttpSession with GemFire (P2P) Sample Application.

Updating Dependencies

Before using Spring Session, you must ensure that the required dependencies are included. If you are using Maven, include the following dependencies in your pom.xml:

pom.xml
<dependencies>
        <!-- ... -->

        <dependency>
                <groupId>org.springframework.session</groupId>
                <artifactId>spring-session-data-gemfire</artifactId>
                <version>1.3.0.RELEASE</version>
                <type>pom</type>
        </dependency>
        <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.3.4.RELEASE</version>
        </dependency>
</dependencies>

Spring Java Configuration

After adding the required dependencies and repository declarations, we can create our Spring configuration. The Spring configuration is responsible for creating a Servlet Filter that replaces the HttpSession with an implementation backed by Spring Session and GemFire.

Add the following Spring Configuration:

@EnableGemFireHttpSession (1)
public class Config {

        @Bean
        Properties gemfireProperties() { (2)
                Properties gemfireProperties = new Properties();

                gemfireProperties.setProperty("name", "GemFireP2PHttpSessionSample");
                gemfireProperties.setProperty("mcast-port", "0");
                gemfireProperties.setProperty("log-level",
                                System.getProperty("sample.httpsession.gemfire.log-level", "warning"));
                gemfireProperties.setProperty("jmx-manager", "true");
                gemfireProperties.setProperty("jmx-manager-start", "true");

                return gemfireProperties;
        }

        @Bean
        CacheFactoryBean gemfireCache() { (3)
                CacheFactoryBean gemfireCache = new CacheFactoryBean();

                gemfireCache.setClose(true);
                gemfireCache.setProperties(gemfireProperties());

                return gemfireCache;
        }
}
1 The @EnableGemFireHttpSession annotation creates a Spring bean named springSessionRepositoryFilter that implements Filter. The filter is what replaces the HttpSession with an implementation backed by Spring Session. In this instance, Spring Session is backed by GemFire.
2 Then, we configure a GemFire peer cache using standard GemFire System properties. We give the GemFire data node a name using the name property and set mcast-port to 0. With the absence of a locators property, this data node will be a standalone server. GemFire’s log-level is set using an application-specific System property (sample.httpsession.gemfire.log-level) that a user can specify on the command-line when running this sample application using either Maven or Gradle (default is "warning").
3 Finally, we create an instance of the GemFire peer cache that embeds GemFire in the same JVM process as the running Spring Session sample application.
Additionally, we have configured this data node (server) as a GemFire Manager as well using GemFire-specific JMX System properties that enable JMX client (e.g. Gfsh) to connect to this running data node.
For more information on configuring Spring Data GemFire, refer to the reference guide.

The @EnableGemFireHttpSession annotation enables a developer to configure certain aspects of Spring Session and GemFire out-of-the-box using the following attributes:

  • maxInactiveIntervalInSeconds - controls HttpSession idle-timeout expiration (defaults to 30 minutes).

  • regionName - specifies the name of the GemFire Region used to store HttpSession state (defaults is "ClusteredSpringSessions").

  • serverRegionShort - specifies GemFire data management policies with a GemFire RegionShortcut (default is PARTITION).

clientRegionShort is ignored in a peer cache configuration and only applies when a client-server topology, and more specifically, a GemFire client cache is used.

Java Servlet Container Initialization

Our Spring Java Configuration created a Spring bean named springSessionRepositoryFilter that implements Filter. The springSessionRepositoryFilter bean is responsible for replacing the HttpSession with a custom implementation backed by Spring Session and GemFire.

In order for our Filter to do its magic, Spring needs to load our Config class. We also need to ensure our Servlet Container (i.e. Tomcat) uses our springSessionRepositoryFilter for every request. Fortunately, Spring Session provides a utility class named AbstractHttpSessionApplicationInitializer to make both of these steps extremely easy.

You can find an example below:

src/main/java/sample/Initializer.java
public class Initializer extends AbstractHttpSessionApplicationInitializer { (1)

        public Initializer() {
                super(Config.class); (2)
        }
}
The name of our class (Initializer) does not matter. What is important is that we extend AbstractHttpSessionApplicationInitializer.
1 The first step is to extend AbstractHttpSessionApplicationInitializer. This ensures that a Spring bean named springSessionRepositoryFilter is registered with our Servlet Container and used for every request.
2 AbstractHttpSessionApplicationInitializer also provides a mechanism to easily allow Spring to load our Config.

HttpSession with GemFire (P2P) Sample Application

Running the httpsession-gemfire-p2p Sample Application

You can run the sample by obtaining the source code and invoking the following command:

$ ./gradlew :samples:httpsession-gemfire-p2p:tomcatRun [-Dsample.httpsession.gemfire.log-level=info]

You should now be able to access the application at http://localhost:8080/

Exploring the httpsession-gemfire-p2p Sample Application

Try using the application. Fill out the form with the following information:

  • Attribute Name: username

  • Attribute Value: john

Now click the Set Attribute button. You should now see the values displayed in the table.

How does it work?

We interact with the standard HttpSession in the SessionServlet shown below:

src/main/java/sample/SessionServlet.java
@WebServlet("/session")
public class SessionServlet extends HttpServlet {

        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                        throws ServletException, IOException {
                String attributeName = request.getParameter("attributeName");
                String attributeValue = request.getParameter("attributeValue");
                request.getSession().setAttribute(attributeName, attributeValue);
                response.sendRedirect(request.getContextPath() + "/");
        }

        private static final long serialVersionUID = 2878267318695777395L;
}

Instead of using Tomcat’s HttpSession, we are actually persisting the values in GemFire. Spring Session creates a cookie named SESSION in your browser that contains the id of your session. Go ahead and view the cookies (click for help with Chrome or Firefox).

The following instructions assume you have a local GemFire installation. For more information on installation, see Installing Pivotal GemFire.

If you like, you can easily remove the session using gfsh. For example, on a Linux-based system type the following at the command-line:

$ gfsh

Then, enter the following into Gfsh ensuring to replace 70002719-3c54-4c20-82c3-e7faa6b718f3 with the value of your SESSION cookie, or the session ID returned by the GemFire OQL query (which should match):

gfsh>connect --jmx-manager=localhost[1099]

gfsh>query --query='SELECT * FROM /ClusteredSpringSessions.keySet'

Result     : true
startCount : 0
endCount   : 20
Rows       : 1

Result
------------------------------------
70002719-3c54-4c20-82c3-e7faa6b718f3

NEXT_STEP_NAME : END

gfsh>remove --region=/ClusteredSpringSessions --key="70002719-3c54-4c20-82c3-e7faa6b718f3"
The GemFire User Guide has more detailed instructions on using gfsh.

Now visit the application at http://localhost:8080/ and observe that the attribute we added is no longer displayed.