Web Application Stack Travel-Spring Distributed Session

1. Implementation of Distributed Session with Edits

In the framework of micro-service, we need to support distributed Session. Distributed Session can be implemented by Redis or database. This paper introduces the implementation of Redis.

II. Installation of Redis

Download address: https://github.com/MSOpenTech...
Select the appropriate version to install.

Go to the installation directory and start Redis.

III. pom Files

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

IV. yml Configuration

The yml configuration is as follows:

# Redis server address
spring.redis.host=localhost
# Redis Server Connection Port
spring.redis.port=6379

Config configuration

The config configuration is as follows:

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400 * 30)
public class SessionConfig {

}

6. Setting Session after landing

Set up Session information after successful landing. The code is as follows:

@Component
@RestController
public class LoginController {

    @RequestMapping("/login")
    public String login(@RequestBody String userId, HttpSession  session) throws Exception {
        session.setAttribute(Constants.SESSION_USER_ID, userId);
        return "Login success.";
    }
}

Session Authentication Filter

Failing to log in successfully and set up Session, you need to jump to the error page. The code example is as follows:

@Configuration
public class SessionFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        if (isNeedAuth(request)) {
            Object userIdObject = request.getSession().getAttribute(Constants.SESSION_USER_ID);
            if (null == userIdObject) {
                response.sendRedirect("/errorPage");
            }
        }

        filterChain.doFilter(request, response);
    }
}

In order to achieve all the steps of Redis Session, the complete code is added to the public address and reply to: webfullstack, get the address of the warehouse.

end.

Site: http://javashizhan.com/

Public address:

<font color="#F4B183"> Join the knowledge planet, participate in the discussion, and share more actual combat code! </font>
https://t.zsxq.com/RNzfi2j

Tags: Java Session Redis Spring Database

Posted on Sun, 06 Oct 2019 07:15:07 -0700 by EagerWolf