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

The completed guide can be found in the HttpSession with GemFire (Client/Server) 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.2.1.RELEASE</version>
                <type>pom</type>
        </dependency>
        <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.2.5.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(maxInactiveIntervalInSeconds = 30) (1)
public class ClientConfig {

        static final long DEFAULT_WAIT_DURATION = TimeUnit.SECONDS.toMillis(20);
        static final long DEFAULT_WAIT_INTERVAL = 500L;

        static final CountDownLatch latch = new CountDownLatch(1);

        static {
                System.setProperty("gemfire.log-level", logLevel());

                ClientMembership.registerClientMembershipListener(
                        new ClientMembershipListenerAdapter() {
                                public void memberJoined(ClientMembershipEvent event) {
                                        if (!event.isClient()) {
                                                latch.countDown();
                                        }
                                }
                        });
        }

        private static String logLevel() {
                return System.getProperty("sample.httpsession.gemfire.log-level", "warning");
        }

        @Bean
        static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
                return new PropertySourcesPlaceholderConfigurer();
        }

        @Bean
        Properties gemfireProperties() { (2)
                return new Properties();
        }

        @Bean
        ClientCacheFactoryBean gemfireCache() { (4)
                ClientCacheFactoryBean clientCacheFactory = new ClientCacheFactoryBean();

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

                return clientCacheFactory;
        }

        @Bean
        PoolFactoryBean gemfirePool((3)
                        @Value("${spring.session.data.gemfire.port:" + ServerConfig.SERVER_PORT + "}") int port) {

                PoolFactoryBean poolFactory = new PoolFactoryBean();

                poolFactory.setFreeConnectionTimeout(5000); // 5 seconds
                poolFactory.setKeepAlive(false);
                poolFactory.setMaxConnections(ServerConfig.MAX_CONNECTIONS);
                poolFactory.setPingInterval(TimeUnit.SECONDS.toMillis(5));
                poolFactory.setReadTimeout(2000); // 2 seconds
                poolFactory.setRetryAttempts(2);
                poolFactory.setSubscriptionEnabled(true);
                poolFactory.setThreadLocalConnections(false);

                poolFactory.setServers(Collections.singletonList(
                        new ConnectionEndpoint(ServerConfig.SERVER_HOSTNAME, port)));

                return poolFactory;
        }

        @Bean
        BeanPostProcessor gemfireCacheServerReadyBeanPostProcessor((5)
                        @Value("${spring.session.data.gemfire.port:" + ServerConfig.SERVER_PORT + "}") final int port) {

                return new BeanPostProcessor() {

                        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
                                if (bean instanceof PoolFactoryBean || bean instanceof Pool) {
                                        Assert.isTrue(waitForCacheServerToStart(ServerConfig.SERVER_HOSTNAME, port),
                                                String.format("GemFire Server failed to start [hostname: %1$s, port: %2$d]",
                                                        ServerConfig.SERVER_HOSTNAME, port));
                                }

                                return bean;
                        }

                        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                                if (bean instanceof PoolFactoryBean || bean instanceof Pool) {
                                        try {
                                                latch.await(DEFAULT_WAIT_DURATION, TimeUnit.MILLISECONDS);
                                        }
                                        catch (InterruptedException e) {
                                                Thread.currentThread().interrupt();
                                        }
                                }

                                return bean;
                        }
                };
        }
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 Next, we register a Properties bean that allows us to configure certain aspects of the GemFire client cache using GemFire’s System properties.
3 Then, we configure a Pool of client connections to talk to the GemFire Server in our Client/Server topology. In our configuration, we have used sensible settings for timeouts, number of connections and so on. Also, the Pool has been configured to connect directly to a server. Learn more about various Pool configuration settings from the PoolFactory API.
4 After configuring a Pool, we create an instance of the GemFire client cache using the GemFire Properties and Pool to communicate with the server and perform cache data access operations.
5 Finally, we include a Spring BeanPostProcessor to block the client until our GemFire Server is up and running, listening for and accepting client connections.

The gemfireCacheServerReadyBeanPostProcessor is necessary in order to coordinate the client and server in an automated fashion during testing, but unnecessary in situations where the GemFire cluster is already presently running, such as in production. This BeanPostProcessor implements 2 approaches to ensure our server has adequate time to startup.

The first approach uses a timed wait, checking at periodic intervals to determine whether a client Socket connection can be made to the server’s CacheServer endpoint.

The second approach uses a GemFire ClientMembershipListener that will be notified when the client has successfully connected to the server. Once a connection has been established, the listener releases the latch that the BeanPostProcessor will wait on (up to the specified timeout) in the postProcessAfterInitialization callback to block the client. Either one of these approaches are sufficient by themselves, but both are demonstrated here to illustrate how this might work and to give you ideas, or other options in practice.

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.

The @EnableGemFireHttpSession annotation enables a developer to configure certain aspects of both 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").

  • clientRegionShort - specifies GemFire data management policies with a GemFire ClientRegionShortcut (default is PROXY).

It is important to note that the GemFire client Region name must match a server Region by the same name if the client Region is a PROXY or CACHING_PROXY. Names are not required to match if the client Region used to store Spring Sessions is LOCAL, however, keep in mind that your session state will not be propagated to the server and you lose all benefits of using GemFire to store and manage distributed, replicated session state information in a cluster.
serverRegionShort is ignored in a client/server cache configuration and only applies when a peer-to-peer (P2P) topology, and more specifically, a GemFire peer cache is used.

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 up to the server to manage.

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

@EnableGemFireHttpSession(maxInactiveIntervalInSeconds = 30) (1)
public class ServerConfig {

        static final int MAX_CONNECTIONS = 50;
        static final int SERVER_PORT = 12480;

        static final String SERVER_HOSTNAME = "localhost";

        @Bean
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
                return new PropertySourcesPlaceholderConfigurer();
        }

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

                gemfireProperties.setProperty("name", "GemFireClientServerHttpSessionSample");
                gemfireProperties.setProperty("mcast-port", "0");
                gemfireProperties.setProperty("log-level", logLevel());
                gemfireProperties.setProperty("jmx-manager", "true");
                gemfireProperties.setProperty("jmx-manager-start", "true");

                return gemfireProperties;
        }

        private String logLevel() {
                return System.getProperty("sample.httpsession.gemfire.log-level", "warning");
        }

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

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

                return gemfireCache;
        }

        @Bean
        CacheServerFactoryBean gemfireCacheServer(Cache gemfireCache, (4)
                        @Value("${spring.session.data.gemfire.port:" + SERVER_PORT + "}") int port) {

                CacheServerFactoryBean cacheServerFactory = new CacheServerFactoryBean();

                cacheServerFactory.setAutoStartup(true);
                cacheServerFactory.setBindAddress(SERVER_HOSTNAME);
                cacheServerFactory.setCache(gemfireCache);
                cacheServerFactory.setHostNameForClients(SERVER_HOSTNAME);
                cacheServerFactory.setMaxConnections(MAX_CONNECTIONS);
                cacheServerFactory.setPort(port);

                return cacheServerFactory;
        }

        @SuppressWarnings("resource")
        public static void main(final String[] args) throws IOException { (5)
                new AnnotationConfigApplicationContext(ServerConfig.class).registerShutdownHook();
        }

}
1 On the server, we also configure Spring Session using the @EnableGemFireHttpSession annotation. For one, this ensures that the Region names on both the client and server match (in this sample, we use the default "ClusteredSpringSessions"). We have also set the session timeout to 30 seconds. Later, we will see how this timeout is used.
2 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.
3 Then, we create an instance of the GemFire peer cache using our GemFire System properties.
4 We also setup a GemFire CacheServer instance running on localhost, listening on port 12480, to accept our client connection.
5 Finally, we declare a main method as an entry point for launching and running our GemFire Server from the command-line.

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 ClientConfig 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(ClientConfig.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 ClientConfig.

HttpSession with GemFire (Client/Server) Sample Application

Running the httpsession-gemfire-clientserver 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:run [-Dsample.httpsession.gemfire.log-level=info]

Then, in a separate terminal, you run the client using:

$ ./gradlew :samples:httpsession-gemfire-clientserver: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 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 expire and timeout, and then refresh the page. 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.