This guide describes how to configure Apache Geode as a provider in Spring Session to transparently manage
a Web application’s javax.servlet.http.HttpSession
using XML Configuration.
The completed guide can be found in the Spring XML Configuation. |
1. 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
:
<dependencies>
<!-- ... -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-geode</artifactId>
<version>2.7.2</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.31</version>
</dependency>
</dependencies>
2. Spring XML Configuration
After adding the required dependencies and repository declarations, we can create the Spring configuration.
The Spring configuration is responsible for creating a Servlet
Filter
that replaces the
javax.servlet.http.HttpSession
with an implementation backed by Spring Session and Apache Geode.
2.1. Client Configuration
Add the following Spring configuration:
<context:annotation-config/>
<context:property-placeholder/>
<bean class="sample.client.ClientServerReadyBeanPostProcessor"/>
(1)
<util:properties id="gemfireProperties">
<prop key="log-level">${spring.data.gemfire.cache.log-level:error}</prop>
</util:properties>
(2)
<gfe:client-cache properties-ref="gemfireProperties" pool-name="gemfirePool"/>
(3)
<gfe:pool read-timeout="15000" retry-attempts="1" subscription-enabled="true">
<gfe:server host="localhost" port="${spring.data.gemfire.cache.server.port:40404}"/>
</gfe:pool>
(4)
<bean class="org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration"
p:poolName="DEFAULT"/>
1 | (Optional) First, we can include a Properties bean to configure certain aspects of the Apache Geode ClientCache
using Pivotal GemFire Properties. In this case, we are just
setting Apache Geode’s “log-level” using an application-specific System property, defaulting to “warning”
if unspecified. |
2 | We must create an instance of an Apache Geode ClientCache . We initialize it with our gemfireProperties . |
3 | Then we configure a Pool of connections to talk to the Apache Geode 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 the server (using the nested gfe:server element). |
4 | Finally, a GemFireHttpSessionConfiguration bean is registered to enable Spring Session functionality. |
In typical Apache Geode production deployments, where the cluster includes potentially hundreds or thousands of servers (a.k.a. data nodes), it is more common for clients to connect to 1 or more Apache Geode Locators running in the same cluster. A Locator passes meta-data to clients about the servers available in the cluster, the individual server load and which servers have the client’s data of interest, which is particularly important for direct, single-hop data access and latency-sensitive applications. See more details about the Client/Server Deployment in the Apache Geode User Guide. |
For more information on configuring Spring Data for Apache Geode, refer to the Reference Guide. |
2.2. Server Configuration
So far, we only covered one side of the equation. We also need an Apache Geode Server for our cache client to talk to and send session state to the server to manage.
In this sample, we will use the following XML configuration to spin up an Apache Geode Server:
<context:annotation-config/>
<context:property-placeholder/>
(1)
<util:properties id="gemfireProperties">
<prop key="name">SpringSessionDataGeodeSampleXmlServer</prop>
<prop key="log-level">${spring.data.gemfire.cache.log-level:error}</prop>
</util:properties>
(2)
<gfe:cache properties-ref="gemfireProperties"/>
(3)
<gfe:cache-server port="${spring.data.gemfire.cache.server.port:40404}"/>
(4)
<bean class="org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration"
p:maxInactiveIntervalInSeconds="30"/>
1 | (Optional) First, we can include a Properties bean to configure certain aspects of the Apache Geode peer Cache
using Pivotal GemFire Properties. In this case, we are just
setting Apache Geode’s “log-level” using an application-specific System property, defaulting to “warning”
if unspecified. |
2 | We must configure an Apache Geode peer Cache instance. We initialize it with the Apache Geode properties. |
3 | Next, we define a CacheServer with sensible configuration for bind-address and port used by our cache client
application to connect to the server and send session state. |
4 | Finally, we enable the same Spring Session functionality we declared in the client XML configuration
by registering an instance of GemFireHttpSessionConfiguration , except we set the session expiration timeout
to 30 seconds. We explain what this means later. |
The Apache Geode Server gets bootstrapped with the following:
@Configuration (1)
@ImportResource("META-INF/spring/session-server.xml") (2)
public class GemFireServer {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(GemFireServer.class).registerShutdownHook();
}
}
Rather than defining a simple Java class with a main method, you might consider using Spring Boot instead.
|
1 | The @Configuration annotation designates this Java class as a source of Spring configuration meta-data using
7.9. Annotation-based container configuration[Spring’s annotation configuration support]. |
2 | Primarily, the configuration comes from the META-INF/spring/session-server.xml file. |
3. XML Servlet Container Initialization
Our Spring XML Configuration created a Spring bean named springSessionRepositoryFilter
that implements javax.servlet.Filter
interface. The springSessionRepositoryFilter
bean is responsible for replacing
the javax.servlet.http.HttpSession
with a custom implementation that is provided by Spring Session and Apache Geode.
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:
<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:
<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>
</filter-mapping>
The DelegatingFilterProxy
will look up a bean by the name of springSessionRepositoryFilter
and cast it to a Filter
. For every HTTP request,
the DelegatingFilterProxy
is invoked, which delegates to the springSessionRepositoryFilter
.
4. HttpSession with Apache Geode (Client/Server) using XML Sample Application
4.1. 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 :spring-session-sample-javaconfig-gemfire-clientserver:run
Now, in a separate terminal, you can run the client using:
$ ./gradlew :spring-session-sample-javaconfig-gemfire-clientserver:tomcatRun
You should now be able to access the application at http://localhost:8080/.
In this sample, the Web application is the Apache Geode cache client and the server is a standalone, separate JVM process.
4.2. 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.
4.3. How does it work?
We interact with the standard HttpSession
in the SessionServlet
shown below:
public class SessionServlet extends HttpServlet {
private static final long serialVersionUID = 2878267318695777395L;
@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() + "/");
}
}
Instead of using Tomcat’s HttpSession
, we are actually persisting the Session in Apache Geode.