博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Session Management – Spring Session JDBC
阅读量:2533 次
发布时间:2019-05-11

本文共 10695 字,大约阅读时间需要 35 分钟。

Spring Session Module provides APIs and implementation for managing user session in a .

Spring Session Module提供用于管理用户会话的API和实现。

Spring会议 (Spring Session)

Spring Session consists of following modules:

Spring Session由以下模块组成:

  1. Spring Session Core: Provides API and core support for session management.

    Spring Session Core:为会话管理提供API和核心支持。
  2. Spring Session JDBC: provides session management using relational database.

    Spring Session JDBC:使用关系数据库提供会话管理。
  3. Spring Session Data Redis: provides session management implementation for Redis database.

    Spring Session Data Redis:为Redis数据库提供会话管理实现。
  4. Spring Session Hazelcast: provides session management support using Hazelcast.

    Spring Session Hazelcast:使用Hazelcast提供会话管理支持。

Spring会议的好处 (Spring Session Benefits)

  • Spring Session decouples session management logic from the application, making it more fault tolerant.

    Spring Session将会话管理逻辑与应用程序分离开来,从而使其更具容错能力。
  • Spring Session keeps user session information in the database, so it’s great to use in a clustered environment with multiple server nodes. We don’t need the sticky session or session replication logic.

    Spring Session将用户会话信息保留在数据库中,因此,在具有多个服务器节点的集群环境中使用它非常好。 我们不需要粘性会话或会话复制逻辑。
  • User session data is not lost if the application crashes. When the application is started again it picks up all the user session data.

    如果应用程序崩溃,则用户会话数据不会丢失。 再次启动该应用程序时,它将获取所有用户会话数据。
  • It’s easy to switch between session storage software, just by changing some configuration we can switch from using to .

    在会话存储软件之间切换很容易,只需更改一些配置,我们就可以从使用切换到 。
  • Spring is an open source project and easily bootstrapped. If you face any issues, there is a good chance that you will find the solution easily online.

    Spring是一个开源项目,很容易引导。 如果您遇到任何问题,很有可能会在网上轻松找到解决方案。

Spring Session JDBC示例 (Spring Session JDBC Example)

Let’s create a simple Spring Session JDBC example project. I will use and MySQL database in the application. So we would need following dependencies in our project.

让我们创建一个简单的Spring Session JDBC示例项目。 我将在应用程序中使用和MySQL数据库。 因此,我们需要在项目中遵循以下依赖关系。

  • spring-boot-starter-web: It’s a web application.

    spring-boot-starter-web:这是一个 Web应用程序。
  • spring-boot-starter-jdbc: For Spring Boot JDBC support and auto configuration.

    spring-boot-starter-jdbc:用于Spring Boot JDBC支持和自动配置。
  • spring-boot-starter-thymeleaf: This is to support Thymeleaf for our view pages. Thymeleaf is simple to use and provides good integration with Spring framework.

    spring-boot-starter-thymeleaf:这是为了在我们的视图页面上支持Thymeleaf。 Thymeleaf易于使用,并与Spring框架提供良好的集成。
  • spring-session-core: Spring Session Core API

    spring-session-core:Spring Session Core API
  • spring-session-jdbc: Spring Session JDBC Implementation

    spring-session-jdbc:Spring Session JDBC实现
  • mysql-connector-java: MySQL JDBC Driver Jar

    mysql-connector-java:MySQL JDBC驱动程序Jar

Here is our final pom.xml file:

这是我们最终的pom.xml文件:

4.0.0
com.journaldev.spring
Spring-Session-Example
0.0.1-SNAPSHOT
jar
Spring-Session-Example
Spring Session Example
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
UTF-8
UTF-8
10
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.session
spring-session-core
org.springframework.session
spring-session-jdbc
mysql
mysql-connector-java
org.springframework.boot
spring-boot-maven-plugin

You can generate the base maven project using Spring Initializr and then add required dependencies.

您可以使用Spring Initializr生成基础Maven项目,然后添加所需的依赖项。

Below image shows the final project structure from Spring Tool Suite.

下图显示了Spring Tool Suite的最终项目结构。

Let’s look at each of the components one by one.

让我们一一看一下每个组件。

application.properties (application.properties)

This is where we specify our database configuration and some spring session attributes.

这是我们指定数据库配置和一些spring会话属性的地方。

spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/SpringSessionDBspring.datasource.username=journaldevspring.datasource.password=journaldevspring.session.store-type=jdbcspring.session.jdbc.initialize-schema=alwaysspring.session.timeout.seconds=900

I am specifying spring.session.jdbc.initialize-schema to always so that Spring will create the required tables for us.

我将spring.session.jdbc.initialize-schema指定为always以便Spring为我们创建所需的表。

Usually, in the production environment, the application user doesn’t have the privilege to execute DDL statements, in that case, set this attribute to never and create database tables manually from the scripts provided in the JAR file.

通常,在生产环境中,应用程序用户没有执行DDL语句的特权,在这种情况下,请将此属性设置为never然后使用JAR文件中提供的脚本手动创建数据库表。

index.html (index.html)

Here is our view page built using Thymeleaf.

这是我们使用Thymeleaf构建的视图页面。

Spring Session JDBC Example

Messages

  • msg

Notice that /saveMessage will be used to send message to server. We will save this message to user session attribute.

请注意, /saveMessage将用于向服务器发送消息。 我们将把此消息保存到用户会话属性。

When the home page is requested, messages attribute will be set to model. So if the user session is valid, we should see all the messages saved on the home page. Spring session uses Cookies to identify user session, so if you hit reload then also you will see all the earlier saved messages.

当请求主页时, messages属性将设置为model。 因此,如果用户会话有效,则应该在主页上看到所有已保存的消息。 Spring会话使用Cookies来标识用户会话,因此,如果您点击reload,那么您还将看到所有先前保存的消息。

Finally, there is a button to invalidate and destroy the session. Once the session is destroyed, it’s attribute will get deleted and you won’t see the earlier saved messages.

最后,有一个按钮可以使会话无效并销毁会话。 一旦会话被销毁,它的属性将被删除,您将看不到之前保存的消息。

HomeController.java (HomeController.java)

This is our controller class where we are handling user requests and saving the message to user session attribute.

这是我们的控制器类,在其中处理用户请求并将消息保存到用户会话属性。

package com.journaldev.spring;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestParam;@Controllerpublic class HomeController {	@GetMapping("/")	public String home(Model model, HttpSession session) {		@SuppressWarnings("unchecked")		List
msgs = (List
) session.getAttribute("MY_MESSAGES"); if (msgs == null) { msgs = new ArrayList<>(); } model.addAttribute("messages", msgs); return "index"; } @PostMapping("/saveMessage") public String saveMessage(@RequestParam("msg") String msg, HttpServletRequest request) { @SuppressWarnings("unchecked") List
msgs = (List
) request.getSession().getAttribute("MY_MESSAGES"); if (msgs == null) { msgs = new ArrayList<>(); request.getSession().setAttribute("MY_MESSAGES", msgs); } msgs.add(msg); request.getSession().setAttribute("MY_MESSAGES", msgs); return "redirect:/"; } @PostMapping("/invalidate") public String destroySession(HttpServletRequest request) { request.getSession().invalidate(); return "redirect:/"; }}

Most of the logic is straightforward, notice that we are not using anything from Spring Session module. This is the beauty of spring framework, it will automatically configure our application to use the database for session management.

大多数逻辑很简单,请注意,我们没有使用Spring Session模块中的任何东西。 这是spring框架的优点,它将自动配置我们的应用程序以使用数据库进行会话管理。

SpringSessionExampleApplication.java (SpringSessionExampleApplication.java)

Just a Spring Boot Application to run our application.

只是一个Spring Boot应用程序来运行我们的应用程序。

package com.journaldev.spring;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class SpringSessionExampleApplication {	public static void main(String[] args) {		SpringApplication.run(SpringSessionExampleApplication.class, args);	}}

Spring Session JDBC测试 (Spring Session JDBC Test)

Our application is ready, just run SpringSessionExampleApplication class as java application. You will notice following mappings in the console logs.

我们的应用程序已准备就绪,只需将SpringSessionExampleApplication类作为Java应用程序运行SpringSessionExampleApplication 。 您会在控制台日志中注意到以下映射。

Mapped "{[/saveMessage],methods=[POST]}" onto public java.lang.String com.journaldev.spring.HomeController.saveMessage(java.lang.String,javax.servlet.http.HttpServletRequest)Mapped "{[/invalidate],methods=[POST]}" onto public java.lang.String com.journaldev.spring.HomeController.destroySession(javax.servlet.http.HttpServletRequest)Mapped "{[/],methods=[GET]}" onto public java.lang.String com.journaldev.spring.HomeController.home(org.springframework.ui.Model,javax.servlet.http.HttpSession)

You will also notice logger for execution of SQL script to create database tables.

您还将注意到记录器执行SQL脚本以创建数据库表。

Executing SQL script from class path resource [org/springframework/session/jdbc/schema-mysql.sql]

You can check these tables in the database too.

您也可以在数据库中检查这些表。

Our index.html page will be automatically configured as the welcome page, as seen in the logs.

如日志所示,我们的index.html页面将被自动配置为欢迎页面。

2018-06-27 12:50:09.761  INFO 1666 --- [main] o.s.b.a.w.s.WelcomePageHandlerMapping: Adding welcome page template: index

Below screen recording shows the output when the application is executed.

下面的屏幕录像显示了执行应用程序时的输出。

摘要 (Summary)

Spring Session is an awesome module that separates session management logic from application logic. It makes our application fault-tolerant and reduces memory usage. It’s very easy to implement and best suited for the clustered environment.

Spring Session是一个很棒的模块,它将会话管理逻辑与应用程序逻辑分开。 它使我们的应用程序具有容错能力,并减少了内存使用量。 它非常容易实现,最适合于集群环境。

. 下载示例代码。

翻译自:

转载地址:http://cdqzd.baihongyu.com/

你可能感兴趣的文章
C6748和音频ADC连接时候的TDM以及I2S格式问题
查看>>
UIView的layoutSubviews,initWithFrame,initWithCoder方法
查看>>
STM32+IAP方案 实现网络升级应用固件
查看>>
用74HC165读8个按键状态
查看>>
jpg转bmp(使用libjpeg)
查看>>
linear-gradient常用实现效果
查看>>
sql语言的一大类 DML 数据的操纵语言
查看>>
VMware黑屏解决方法
查看>>
JS中各种跳转解析
查看>>
JAVA 基础 / 第八课:面向对象 / JAVA类的方法与实例方法
查看>>
Ecust OJ
查看>>
P3384 【模板】树链剖分
查看>>
Thrift源码分析(二)-- 协议和编解码
查看>>
考勤系统之计算工作小时数
查看>>
4.1 分解条件式
查看>>
Equivalent Strings
查看>>
flume handler
查看>>
收藏其他博客园主写的代码,学习加自用。先表示感谢!!!
查看>>
H5 表单标签
查看>>
su 与 su - 区别
查看>>