Spring Session - Spring Boot

本指南介绍了在使用 Spring Boot 时如何使用 Spring Session 透明利用关系数据库来支持 Web 应用程序的 HttpSession

This guide describes how to use Spring Session to transparently leverage a relational database to back a web application’s HttpSession when you use Spring Boot.

您可以在httpsession-jdbc-boot sample application中找到已完成指南。

You can find the completed guide in the httpsession-jdbc-boot-sample.

Updating Dependencies

在使用 Spring Session 之前,必须更新你的依赖项。我们假设你正在与正在运行的 Spring Boot Web 应用程序一起使用。如果你使用 Maven,则必须添加以下依赖项:

Before you use Spring Session, you must update your dependencies. We assume you are working with a working Spring Boot web application. If you use Maven, you must add the following dependencies:

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

	<dependency>
		<groupId>org.springframework.session</groupId>
		<artifactId>spring-session-jdbc</artifactId>
	</dependency>
</dependencies>

Spring Boot 为 Spring Session 模块提供了依赖管理,因此你无需明确声明依赖项版本。

Spring Boot provides dependency management for Spring Session modules, so you need not explicitly declare the dependency version.

Spring Boot Configuration

在添加必需的依赖项后,我们可以创建 Spring Boot 配置。由于一流的自动配置支持,只需添加依赖项,Spring Boot 就为我们设置了关系数据库支持的 Spring Session。

After adding the required dependencies, we can create our Spring Boot configuration. Thanks to first-class auto-configuration support, just by adding the dependency Spring Boot will set up Spring Session backed by a relational database for us.

如果 classpath 上存在单个 Spring Session 模块,Spring Boot 会自动使用该存储实现。如果你有多个实现,你必须选择要用于存储会话的 StoreType,如上所示。

If a single Spring Session module is present on the classpath, Spring Boot uses that store implementation automatically. If you have more than one implementation, you must choose the StoreType that you wish to use to store the sessions, as shows above.

在表面之下,Spring Boot 应用的配置等同于手动添加 @EnableJdbcHttpSession 注解。这创建了一个名为 springSessionRepositoryFilter 的 Spring bean。该 bean 实现了 Filter。该筛选器负责替换 HttpSession 实现,以便由 Spring Session 支持。

Under the hood, Spring Boot applies configuration that is equivalent to manually adding the @EnableJdbcHttpSession annotation. This creates a Spring bean with the name of springSessionRepositoryFilter. That bean implements Filter. The filter is in charge of replacing the HttpSession implementation to be backed by Spring Session.

你可以使用 application.properties 进一步自定义。以下清单显示了如何执行此操作:

You can further customize by using application.properties. The following listing shows how to do so:

src/main/resources/application.properties
server.servlet.session.timeout= # Session timeout. If a duration suffix is not specified, seconds are used.
spring.session.jdbc.initialize-schema=embedded # Database schema initialization mode.
spring.session.jdbc.schema=classpath:org/springframework/session/jdbc/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema.
spring.session.jdbc.table-name=SPRING_SESSION # Name of the database table used to store sessions.

有关更多信息,请参阅 Spring Boot 文档中的 {docs-url}/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-session[Spring Session] 部分。

For more information, see the {docs-url}/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-session[Spring Session] portion of the Spring Boot documentation.

Configuring the DataSource

Spring Boot 自动创建 DataSource,它将 Spring Session 连接到 H2 数据库的嵌入式实例。在生产环境中,你需要更新配置以指向你的关系数据库。例如,你可以在 application.properties 中包含以下内容:

Spring Boot automatically creates a DataSource that connects Spring Session to an embedded instance of an H2 database. In a production environment, you need to update your configuration to point to your relational database. For example, you can include the following in your application.properties:

src/main/resources/application.properties
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.
spring.datasource.password= # Login password of the database.

有关更多信息,请参阅 Spring Boot 文档的 {docs-url}/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-configure-datasource[配置数据源] 部分。

For more information, see the {docs-url}/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-configure-datasource[Configure a DataSource] portion of the Spring Boot documentation.

Servlet Container Initialization

我们的 Spring Boot Configuration 创建了一个名为 springSessionRepositoryFilter 的 Spring bean,它实现了 FilterspringSessionRepositoryFilter bean 负责使用 Spring Session 支持的自定义实现替换 HttpSession

Our httpsession-jdbc-boot-spring-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.

为了让我们的 Filter 发挥作用,Spring 需要加载我们的 Config 类。最后,我们需要确保我们的 Servlet 容器(即 Tomcat)在每个请求中使用我们的 springSessionRepositoryFilter。幸运的是,Spring Boot 替我们执行这两个步骤。

In order for our Filter to do its magic, Spring needs to load our Config class. Last, we need to ensure that our Servlet Container (that is, Tomcat) uses our springSessionRepositoryFilter for every request. Fortunately, Spring Boot takes care of both of these steps for us.

httpsession-jdbc-boot Sample Application

httpsession-jdbc-boot 示例应用程序演示了在使用 Spring Boot 时如何使用 Spring Session 透明利用 H2 数据库来支持 Web 应用程序的 HttpSession

The httpsession-jdbc-boot Sample Application demonstrates how to use Spring Session to transparently leverage an H2 database to back a web application’s HttpSession when you use Spring Boot.

Running the httpsession-jdbc-boot Sample Application

您可以获取 源代码 并调用以下命令运行示例:

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

$ ./gradlew :spring-session-sample-boot-jdbc:bootRun

您现在应该能够访问 [role="bare"][role="bare"]http://localhost:8080/ 中的应用程序。

You should now be able to access the application at [role="bare"]http://localhost:8080/

Exploring the Security Sample Application

您现在可以尝试使用该应用程序。为此,请输入以下内容进行登录:

You can now try using the application. To do so, enter the following to log in:

  • Username user

  • Password password

现在,单击 Login 按钮。你现在应该看到一条消息,指出你已使用之前输入的用户登录。用户的相关信息存储在 H2 数据库中,而不是 Tomcat 的 HttpSession 实现中。

Now click the Login button. You should now see a message indicating that your are logged in with the user entered previously. The user’s information is stored in the H2 database rather than Tomcat’s HttpSession implementation.

How Does It Work?

我们持久化值到 H2 数据库中,而不是使用 Tomcat 的 HttpSession。Spring Session 用一个关系数据库支持的实现替换了 HttpSession。当 Spring Security 的 SecurityContextPersistenceFilterSecurityContext 保存到 HttpSession 中时,它就会持久化到 H2 数据库中。

Instead of using Tomcat’s HttpSession, we persist the values in the H2 database. Spring Session replaces the HttpSession with an implementation that is backed by a relational database. When Spring Security’s SecurityContextPersistenceFilter saves the SecurityContext to the HttpSession, it is then persisted into the H2 database.

当创建新的 HttpSession 时,Spring Session 在浏览器中创建一个名为 SESSION 的 cookie。该 cookie 包含会话 ID。您可以查看 cookie(使用 ChromeFirefox)。

When a new HttpSession is created, Spring Session creates a cookie named SESSION in your browser. That cookie contains the ID of your session. You can view the cookies (with Chrome or Firefox).

你可以使用位于 [role="bare"][role="bare"]http://localhost:8080/h2-console/ 的 H2 web 控制台来移除会话(为 JDBC URL 使用 jdbc:h2:mem:testdb)。

You can remove the session by using the H2 web console available at: [role="bare"]http://localhost:8080/h2-console/ (use jdbc:h2:mem:testdb for JDBC URL).

现在,您可以访问 [role="bare"][role="bare"]http://localhost:8080/ 中的应用程序并看到我们不再通过身份验证。

Now you can visit the application at [role="bare"]http://localhost:8080/ and see that we are no longer authenticated.