Store session information in database in Spring Session

What is Spring Session?

You can overwrite the function of HttpSession and manage session information with Redis, RDBMS, etc. Normally, session information is managed by the application server, but if multiple servers are prepared and operated while load balancing, session information is synchronized between multiple servers (session replication), or user and server. It is necessary to load balance so that there is a one-to-one relationship (sticky session), which is troublesome.

Therefore, Spring Session can be used nicely when you want to cut out session information to a place other than the application server.

Use Spring Session

Creating a project

Create a Spring Boot project with Spring Initializr. https://start.spring.io/

This time, I added the following as Dependencies.

The RDBMS that stores session information is PostgreSQL.

application.properties

application.properties


spring.session.store-type=jdbc
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver

If you set spring.session.store-type to jdbc, it feels like SpringSession related settings are done without permission. No, Spring Boot is convenient. (Specify the datasource setting according to the environment.)

Database setup

There seems to be a way to set it up automatically, but I'm not sure how to do it, so I will create a table to store session information. There is a sql file in SpringSessionJdbc, so you can run it. https://github.com/spring-projects/spring-session/tree/master/spring-session-jdbc/src/main/resources/org/springframework/session/jdbc

Try to operate the session

I created the following Controller class and tried to manipulate the session information.

HelloController.java


@Controller
public class HelloController {

	@Autowired
	SessionData sessionData;

	@GetMapping(value = "/")
	public String index() {
		return "index";
	}

	@GetMapping(value="/set")
	public String set(){
		sessionData.setStr1("hogehoge");
		sessionData.setStr2("fugafuga");
		sessionData.setStr3("piyopiyo");
		return "redirect:/";
	}
}

SessionData.java


@Data
@Component
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class SessionData implements Serializable{
    private static final long serialVersionUID = 1L;
    String str1;
    String str2;
    String str3;
}

index.html


<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8" />
    <title>Hello Thymeleaf</title>
</head>

<body>
    <div>
        str1:
        <span th:text="${@sessionData.str1}">aaa</span>
    </div>
    <div>
        str2:
        <span th:text="${@sessionData.str2}">aaa</span>
    </div>
    <div>
        str3:
        <span th:text="${@sessionData.str3}">aaa</span>
    </div>
    <form th:action="@{/set}" method="get">
        <button>set</button>
    </form>
</body>

</html>

For implementation, you can operate the session as usual. If you check the database, you can see that the session information is held there.

Since the data is serialized and stored, it is necessary to implement Serializable for session information.


As mentioned above, session information can be easily stored in RDBMS. Personally, I thought it would be easier to handle various things if the information was stored in JSON. It seems that the data conversion part can be customized, but I gave up because it seems to be difficult to change the data type. (Since the DB schema also changes, we have to remake it.)

In addition, it seems that the implementation that uses Redis provides a method to store data in JSON.

Recommended Posts

Store session information in database in Spring Session
Error in Spring database connection
Change session timeout time in Spring Boot
Inject Logger in Spring
Use Interceptor in Spring
Microservices in Spring Cloud
Get cookies in Spring
SerializationException in Spring Boot (1 series) + spring-security-oauth2 + Redis Session + Heroku
Database environment construction with Docker in Spring boot (IntellJ)
Get error information using DefaultErrorAttributes and ErrorAttributeOptions in Spring Boot 2.3
[Rails] How to display information stored in the database in view
Set context-param in Spring Boot
Get EXIF information in Java
Spring Boot 2 multi-project in Gradle
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Loop step in Spring Batch
How to store the information entered in textarea in a variable in the method