Table of Contents
Problem:
Solution:
1. Change the configuration file according to the posts on the Internet (if it is started by Jar, it will take effect), as follows:
2. Set the session timeout of tomcat
The huge pit that causes Spring session failure due to time out-of-synchronization
In addition, by the way, I will record the Linux server time synchronization
Home Java javaTutorial How to solve the problem that the Springboot2 session timeout setting is invalid

How to solve the problem that the Springboot2 session timeout setting is invalid

May 22, 2023 pm 01:49 PM
session springboot

Problem:

Today, I encountered a setting timeout problem in the project. The application.properties changes of SpringBoot2 never took effect.

Solution:

  • The embedded container used by Spring Boot is controlled by the server.* properties. Spring Boot will create an instance of the servlet container using one of the ServletWebServerFactory instances. These classes use server.* attributes to configure managed servlet containers (such as Tomcat, Jetty, etc.).

  • When the application is packaged into a war file and deployed to a Tomcat instance, the server.* attributes cannot be used. These do not apply as the prefabricated servlet container can be leveraged (since the service is running remotely). Therefore, deploying to a remote Tomcat will render the server.* properties useless.

1. Change the configuration file according to the posts on the Internet (if it is started by Jar, it will take effect), as follows:

server:
  servlet:
    session:
      timeout: PT1H        # 1小时过期
      cookie:
        max-age: PT1H      # 1小时过期
Copy after login

Note: PT1H means that the time to set the session expiration is 1 hour.

Extension: Duration

The setTimeouot method is found by viewing the springboot source code. Here, the instance of Duration is required to be passed in.

public void setTimeout(Duration timeout) {
       this.timeout = timeout;
    }
Copy after login

Duration is new in Java8 and is mainly used for calculation Date difference, Duration is declared final and is thread-safe.

If you convert a string, it is similar to the date formatting method of SimpleDateFormat

Duration. Strings are similar to numbers, which are positive and negative: the default is positive, and negative starts with '-', followed by Then 'PT', the following time letters:

  • 'D' - day

  • 'H' - hour

  • 'M' - Minutes

  • 'S' - Seconds

Each unit must start with a number, and hours and minutes The order of seconds cannot be messed up, for example: PT2H3M2S is equal to -PT-2H-3M-2S.

2. Set the session timeout of tomcat

1) In the conf directory of tomcat, change servler.xml:

<Context path="/abtest" docBase="/abtest"  
  defaultSessionTimeOut="3600" isWARExpanded="true"  
  isWARValidated="false" isInvokerEnabled="true"  
  isWorkDirPersistent="false"/>
Copy after login

2) Change web.xml in the project:

<session-config>  
    <session-timeout>20</session-timeout>  
</session-config>
Copy after login

3) Change in the program

session.setMaxInactiveInterval(30*60);
Copy after login

When you encounter the same problem, please read the red words above and troubleshoot in order.

Test code:

@RestController
@RequestMapping("/valid-time")
public class TestController { 
    @GetMapping("/test")
    public String validTime(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(); 
        int sessionTime = session.getMaxInactiveInterval(); 
        return new StringBuilder("sessionTime=").append(sessionTime).toString();
    }
}
Copy after login

The huge pit that causes Spring session failure due to time out-of-synchronization

The huge pit that causes Spring session failure due to out-of-synchronization of Linux server time

Due to business needs, the original stand-alone environment was converted into a cluster environment. In order not to modify the tasks, spring session redis was chosen as the session sharing solution.

After confirming the technical solution, I searched a lot of information about spring session on the Internet. After reading it and not finding any pitfalls of previous people, I started to work on it.

The redis installation process is ignored.

Add spring session to the project step by step according to the information. The single-node project ran successfully without any errors, and the session was successfully written to redis.

Then for the sake of safety, I installed nginx on my computer and deployed 3 tomcats. Everything looked perfect, and session sharing was completed between multiple nodes.

So far, all the preliminary preparations have been completed, and the last step is just left.

The nightmare begins...

Deploy all nodes online, and then open the browser to successfully access the application. Of course, we can't just stop at the point where we see the page is completed, we have to do it no matter what. Log in and log in, so...

Then...

I entered the user password countless times, prompting that the login was successful, but the final result was still being rejected, o(╥﹏╥)o

The next step is to fill in countless pitfalls

Look at the logs...

Look at various request requests...

I suspect there is a BUG in the spring session... …

Even turned on the remote DEBUG mode debugging, and finally saw in the universal DEBUG mode that when the spring session getsSession, if the session is obtained, will first determine whether the session has expired, compare The method is also very simple, which is to obtain the current system time and compare it with the expiration time of the session. If the current time is less than the expiration time, it indicates that the session has not expired. Seeing this, I instantly felt a sense of enlightenment, and the small universe finally broke out here.

Nima—>All the acquired sessions were expired, and then...then...of course I hurriedly ran to check the server time, so...I cried o(╥﹏╥)o, it turned out to be Nima It was you who tricked me...

In order to commemorate this journey of lying in the trap, I am posting this article

In addition, by the way, I will record the Linux server time synchronization

date command:

date : View the current time, the results are as follows: Tue Mar 4 01:36:45 CST 2017

date -s 09:38:40 :Set the current time, the result is as follows: Tue Mar 4 09:38:40 CST 2017

ntpdate command:

ntpdate -u ntp.api.bz :Network time Synchronization command

ntp commonly used server:

China National Time Service Center: 210.72.145.44

NTP server (Shanghai): ntp.api.bz

The above is the detailed content of How to solve the problem that the Springboot2 session timeout setting is invalid. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to implement SMS login in Redis shared session application How to implement SMS login in Redis shared session application Jun 03, 2023 pm 03:11 PM

1. Implementing SMS login based on session 1.1 SMS login flow chart 1.2 Implementing sending SMS verification code Front-end request description: Description of request method POST request path /user/code request parameter phone (phone number) return value No back-end interface implementation: @Slf4j@ ServicepublicclassUserServiceImplextendsServiceImplimplementsIUserService{@OverridepublicResultsendCode(Stringphone,HttpSessionsession){//1. Verify mobile phone number if

SpringBoot+Dubbo+Nacos development practical tutorial SpringBoot+Dubbo+Nacos development practical tutorial Aug 15, 2023 pm 04:49 PM

This article will write a detailed example to talk about the actual development of dubbo+nacos+Spring Boot. This article will not cover too much theoretical knowledge, but will write the simplest example to illustrate how dubbo can be integrated with nacos to quickly build a development environment.

See all articles