This guide describes how to configure Spring Session to transparently leverage Pivotal GemFire to back a web application’s HttpSession using XML Configuration.

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.2.0.RC3</version>
                <type>pom</type>
        </dependency>
        <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.2.5.RELEASE</version>
        </dependency>
</dependencies>

Since we are using a Milestone version, we need to add the Spring Milestone Maven Repository. If you are using Maven, include the following repository declaration in your pom.xml:

pom.xml
<repositories>
        <!-- ... -->

        <repository>
                <id>spring-milestone</id>
                <url>https://repo.spring.io/libs-milestone</url>
        </repository>
</repositories>

Spring XML 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:

        (1)
        <util:properties id="applicationProperties"
                     location="classpath:META-INF/spring/application.properties"/>

        (2)
        <context:property-placeholder properties-ref="applicationProperties"/>

        (3)
        <context:annotation-config/>

        (4)
        <bean class="org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration"
          p:maxInactiveIntervalInSeconds="30"/>

        (5)
        <bean class="sample.GemFireCacheServerReadyBeanPostProcessor"/>

        (6)
        <util:properties id="gemfireProperties">
                <prop key="log-level">${sample.httpsession.gemfire.log-level:warning}</prop>
        </util:properties>

        <gfe:client-cache properties-ref="gemfireProperties"/>

        (7)
        <gfe:pool free-connection-timeout="5000"
              keep-alive="false"
              ping-interval="5000"
              read-timeout="5000"
              retry-attempts="2"
              subscription-enabled="true"
              thread-local-connections="false"
              max-connections="${application.gemfire.client-server.max-connections}">
                <gfe:server host="${application.gemfire.client-server.host}"
                    port="${spring.session.data.gemfire.port:${application.gemfire.client-server.port}}"/>
        </gfe:pool>
1 First, a Properties bean is created to reference GemFire configuration common to both the client and server, stored in the META-INF/spring/application.properties file.
2 The application.properties are used along with the PropertySourcesPlaceholderConfigurer bean to replace placeholders in the Spring XML configuration meta-data with property values.
3 Spring annotation configuration support is enabled with <context:annotation-config/> element so that any Spring beans declared in the XML config that are annotated with either Spring or Standard Java annotations supported by Spring will be configured appropriately.
4 GemFireHttpSessionConfiguration is registered to enable Spring Session functionality.
5 Then, a Spring BeanPostProcessor is registered to determine whether a GemFire Server at the designated host/port is running, blocking client startup until the server is available.
6 Next, we include a Properties bean to configure certain aspects of the GemFire client cache using GemFire’s System properties. In this case, we are just setting GemFire’s log-level from a sample application-specific System property, defaulting to warning if unspecified.
7 Finally, we create the GemFire client cache and configure a Pool of client connections to talk to the GemFire Server in our Client/Server topology. In our configuration, we use sensible settings for timeouts, number of connections and so on. Also, our Pool has been configured to connect directly to a server.
In typical GemFire deployments, where the cluster includes potentially hundreds of GemFire data nodes (servers), it is more common for clients to connect to one or more GemFire Locators running in the cluster. A Locator passes meta-data to clients about the servers available, load and which servers have the client’s data of interest, which is particularly important for single-hop, direct data access. See more details about the Client/Server Topology in GemFire’s User Guide.
For more information on configuring Spring Data GemFire, refer to the reference guide.

Server Configuration

Now, we have only covered one side of the equation. We also need a GemFire Server for our client to talk to and pass session state information up to the server to manage.

In this sample, we will use the following GemFire Server Java Configuration:

        (1)
        <context:annotation-config/>

        (2)
        <context:property-placeholder location="classpath:META-INF/spring/application.properties"/>

        (3)
        <bean class="org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration"
          p:maxInactiveIntervalInSeconds="30"/>

        (4)
        <util:properties id="gemfireProperties">
                <prop key="name">GemFireClientServerHttpSessionXmlSample</prop>
                <prop key="mcast-port">0</prop>
                <prop key="log-level">${sample.httpsession.gemfire.log-level:warning}</prop>
                <prop key="jmx-manager">true</prop>
                <prop key="jmx-manager-start">true</prop>
        </util:properties>

        (5)
        <gfe:cache properties-ref="gemfireProperties"
               use-bean-factory-locator="false"/>

        (6)
        <gfe:cache-server auto-startup="true"
                      bind-address="${application.gemfire.client-server.host}"
                      port="${spring.session.data.gemfire.port:${application.gemfire.client-server.port}}"
                      max-connections="${application.gemfire.client-server.max-connections}"/>
1 First, we enable Spring annotation config support with the <context:annotation-config> element so that any Spring beans declared in the XML config that are annotated with either Spring or Standard Java annotations supported by Spring will be configured appropriately.
2 A PropertySourcesPlaceholderConfigurer is registered to replace placeholders in our Spring XML configuration meta-data with property values from META-INF/spring/application.properties.
3 We enable the same Spring Session functionality that we used on the client by registering an instance of GemFireHttpSessionConfiguration, except that we set the session expiration timeout to 30 seconds. We will explain later what this means.
4 Next, we configure the GemFire Server using GemFire System properties very much like our P2P samples. With the mcast-port set to 0 and no locators property specified, our server will be standalone. We also allow a JMX client (e.g. Gfsh) to connect to our server with the use of the GemFire-specific JMX System properties.
5 Then, we create an instance of the GemFire peer cache using our GemFire System properties.
6 And finally, we also setup a GemFire CacheServer instance running on localhost, listening on port 11235, to accept our client connection.

The GemFire Server configuration gets bootstrapped with the following:

@Configuration (1)
@ImportResource("META-INF/spring/session-server.xml") (2)
public class Application {

        public static void main(final String[] args) {
                AnnotationConfigApplicationContext context =
                        new AnnotationConfigApplicationContext(Application.class);
                context.registerShutdownHook();
        }
}
Instead of a simple Java class with a main method, you could also use Spring Boot.
1 The @Configuration annotation designates this Java class as a source for Spring configuration meta-data using Spring’s annotation configuration support.
2 Primarily, the configuration comes from the META-INF/spring/session-server.xml file, which is also the reason why Spring Boot was not used in this sample, since using XML seemingly defeats the purpose and benefits of using Spring Boot. However, this sample is about demonstrating how to use Spring XML to configure the GemFire client and server.

XML Servlet Container Initialization

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

In order for our Filter to do its magic, we need to instruct Spring to load our session-client.xml configuration file. We do this with the following configuration:

src/main/webapp/WEB-INF/web.xml
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/session-client.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

The ContextLoaderListener reads the contextConfigLocation context parameter value and picks up our session-client.xml configuration file.

Finally, we need to ensure that our Servlet Container (i.e. Tomcat) uses our springSessionRepositoryFilter for every request.

The following snippet performs this last step for us:

src/main/webapp/WEB-INF/web.xml
<filter>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>ERROR</dispatcher>
    <dispatcher>ASYNC</dispatcher>
</filter-mapping>

The DelegatingFilterProxy will look up a bean by the name of springSessionRepositoryFilter and cast it to a Filter. For every request that DelegatingFilterProxy is invoked, the springSessionRepositoryFilter will be invoked.

HttpSession with GemFire (Client/Server) using XML Sample Application

Running the httpsession-gemfire-clientserver-xml Sample Application

You can run the sample by obtaining the source code and invoking the following commands.

First, you need to run the server using:

$ ./gradlew :samples:httpsession-gemfire-clientserver-xml:run [-Dsample.httpsession.gemfire.log-level=info]

Now, in a separate terminal, you can run the client using:

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

You should now be able to access the application at http://localhost:8080/. In this sample, the web application is the client cache and the server is standalone.

Exploring the httpsession-gemfire-clientserver-xml 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 commands in 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/ again and observe that the attribute we added is no longer displayed.

Alternatively, you can wait 30 seconds for the session to timeout (i.e. expire) and refresh the page. Again, the attribute we added should no longer be displayed in the table. However, keep in mind, that by refreshing the page, you will inadvertently create a new (empty) session. If you run the query again, you will also see two session IDs, the new and the old, since GemFire keeps a "tombstone" of the old session around.