SpringBoot integrates JPA and Redis to realize distributed Session sharing

  1. Creating a Web project

Following our previous experience, we created a Web application and transformed it into a Spring Boot project. The details are omitted.

2. Add a dependency package

3. Create the application.yml configuration file

Server: port: 8080 servlet: # Set session expiration time session: timeout: “PT10M” Spring: Application: name: spring-session-jpa datasource: driver-class-name: com.mysql.cj.jdbc.Driver username: root password: syc url: jdbc:mysql://localhost:3306/spring-security? useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&serverTimezone=UTC redis: host: Localhost port: 6379 database: 0 jedis: pool: max-idle: 8 min-idle: 0 max-active: 8 session: # Redis jPA: database: mysql show-sql: true

4. Create the User entity class

package com.yyg.boot.entity;

import ch.qos.logback.classic.db.names.TableName; import lombok.Data; import lombok.ToString; import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*; import javax.validation.constraints.NotBlank; import java.io.Serializable;

/ * *

  • @author-Brother Sun
  • @Date Created in 2020/4/29
  • @Description Description

*/ @Entity @Table(name=”user”) @Data @ToString public class User implements Serializable {

@Id
@GeneratedValue(generator = "idGenerator",strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "username")
@NotBlank(message = "username can not be empty")
private String username;

@Column(name = "password")
@NotBlank(message = "password can not be empty")
private String password;
Copy the code

}

5. Create UserRepository repository class

package com.yyg.boot.repository;

import com.yyg.boot.entity.User; import org.springframework.data.jpa.repository.JpaRepository;

/ * *

  • @author-Brother Sun
  • @Date Created in 2020/4/29
  • @Description Description

*/ public interface UserRepository extends JpaRepository<User,Long> {

User findByUsername(String username);

User findByUsernameAndPassword(String username,String password);
Copy the code

}

6. Create the Service implementation class

6.1 Creating the UserService Interface

package com.yyg.boot.service;

import com.yyg.boot.entity.User;

/ * *

  • @author-Brother Sun
  • @Date Created in 2020/4/29
  • @Description Description

/ public interface UserService { /* * save user */ User saveUser(User user);

/**
 * find user by account
 */
User findByUsername(String username);

/**
 * user login
 */
User login(String username, String password);
Copy the code

}

6.2 Creating the UserServiceImpl Implementation Class

package com.yyg.boot.service.impl;

import com.yyg.boot.entity.User; import com.yyg.boot.repository.UserRepository; import com.yyg.boot.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;

/ * *

  • @author-Brother Sun
  • @Date Created in 2020/4/29
  • @Description Description

*/ @Service public class UserServiceImpl implements UserService {

@Autowired
private UserRepository userRepository;

@Override
public User saveUser(User user) {
    return userRepository.save(user);
}

@Override
public User findByUsername(String username) {
    return userRepository.findByUsername(username);
}

@Override
public User login(String username, String password) {
    return userRepository.findByUsernameAndPassword(username, password);
}
Copy the code

}

7. Create the UserController interface

package com.yyg.boot.web;

import com.yyg.boot.entity.User; import com.yyg.boot.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/ * *

  • @author-Brother Sun
  • @Date Created in 2020/4/29
  • @Description Description

*/ @RestController @RequestMapping(“/user”) public class UserController {

@Autowired private UserService userService; /** * save user */ @PostMapping(value = "/save") public User save(@RequestBody User user) { return userService.saveUser(user); } /** * find user by username */ @GetMapping(value = "/find/{username}") public User findUser(@PathVariable String username) { return userService.findByUsername(username); } /** * user login */ @GetMapping(value = "/login") public User login(String username, String password, HttpSession session) { User user = userService.login(username, password); if(user! =null){ session.setAttribute(session.getId(),user); } return user; } @GetMapping(value = "/logout") public String logout(HttpSession session){ session.removeAttribute(session.getId()); return "user logout success"; }Copy the code

}

8. Add an interceptor to check whether the session is valid

package com.yyg.boot.config;

import com.alibaba.fastjson.JSON; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException;

/ * *

  • @author-Brother Sun
  • @Date Created in 2020/4/28
  • @description Enables the Redis Http Session

*/ @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800) public class RedisHttpSessionConfiguration implements WebMvcConfigurer {

*/ @override public void addInterceptors(InterceptorRegistry registry) {registry. AddInterceptor (new) ExcludePathPatterns ("/user/login"). ExcludePathPatterns ("/user/logout") // Intercepts the path .addPathPatterns("/**"); */ @configuration public class SecurityInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { HttpSession session = request.getSession(); if (session.getAttribute(session.getId()) ! = null) { return true; } response.getWriter().write(JSON.toJSONString("please login first")); return false; }}Copy the code

}

9. Create an entry class

package com.yyg.boot;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;

/ * *

  • @author-Brother Sun
  • @Date Created in 2020/4/28
  • @Description Description

*/ @SpringBootApplication public class SpringSessionJpaApplication {

Public static void main(String[] args){springApplication.run - This website can be sold. - Best Source of SpringApplication and related information. (SpringSessionJpaApplication.class,args); }Copy the code

}

10. Complete project structure

11. Start the project and test it

When we directly query a user’s information based on the user name without logging in, we will see the browser prompt us to log in first.

Then test the save interface and you will find that it is also prompted to log in first.

At this point, we log in and the login succeeds

We then test the Save or find interfaces and see that they are now accessible.

A new data has been added to the database.

Then we log out again

Then re-test the query interface, and find that the user information cannot be queried, prompting you to log in.

After logging in again, we can start the new process 8081 again and query the user information of Tom. It will be found that the user information of Tom is also queried, indicating that we have realized session sharing.

Redis also has saved session information.

This set of learning content written by Teacher Qian Feng, qian Feng Education Changsha Java Training Institute all copyright, welcome to reprint, please note the author. Thank you very much!