4. Use Redis to optimize login module

#Using Redis to optimize login module

Redis is used to optimize the functions with high access frequency that will affect efficiency

Use Redis to store verification code

[the transfer of external chain pictures fails, and the source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-cyBCi9TJ-1646574106551)(D:\TyporaNotes \ Niuke forum project \ Chapter III pictures \ 4.7.1.png)]

When the user accesses the login interface for the first time, the server generates a random string, saves it in the cookie, sends it to the browser, and generates the corresponding key to save the verification code text to Redis

  • Because the user has not logged in, all users cannot obtain user information, so the temporary certificate is used as the key to access the information;
  • When users visit the login page, they will first send a cookie to the user to store the randomly generated string, which will be used as a temporary credential
  • The effective time of cookie s is set to be relatively short to save expenses. It can be set to 60 seconds;
  • The verification code in Redis is set to expire in 60 seconds to save overhead;
// Login verification code
public static String getKaptchaKey(String owner) {
    return PREFIX_KAPTCHA + SPLIT + owner;
}
//Generate verification code key and save it to cookie
String kaptchaOwner=CommunityUtil.generateUUID();
Cookie cookie=new Cookie("kaptchaOwner",kaptchaOwner);
cookie.setMaxAge(60);
cookie.setPath(contextPath);
httpServletResponse.addCookie(cookie);
//Save the verification code to Redis
String redisKey= RedisKeyUtil.getKaptchaKey(kaptchaOwner);
redisTemplate.opsForValue().set(redisKey,text,60, TimeUnit.SECONDS);
 // Check verification code
// String kaptcha = (String) session.getAttribute("KaptchaCode");
 String kaptcha=null;
 if(StringUtils.isNotBlank(kaptchaOwner))
 {
     String redisKey=RedisKeyUtil.getKaptchaKey(kaptchaOwner);
     kaptcha =(String) redisTemplate.opsForValue().get(redisKey);
 }

Use Redis to store login credentials

// Login credentials
public static String getTicketKey(String ticket) {
    return PREFIX_TICKET + SPLIT + ticket;
}

Set the previous LoginTicketMapper to not recommended

[the transfer of external chain pictures fails, and the source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-YCMus558-1646574106552)(D:\TyporaNotes \ Niuke forum project \ Chapter III pictures \ 4.7.2.png)]

//Redis is used to store login credentials
String redisKey= RedisKeyUtil.getTicketKey(loginTicket.getTicket());
redisTemplate.opsForValue().set(redisKey,loginTicket);

When exiting, set the status of the login credentials to 1. When relocating to Redis, it is not deleted directly because the user login information needs to be saved

//sign out
public void logout(String ticket)
{
    //LoginTicket loginTicket = loginTicketMapper.selectLoginTicket(ticket);
    //System.out.println("expired at exit" + loginticket. Getexpired());
    //loginTicketMapper.updateLoginTicket(ticket,1);
    //Use Redis to modify the status
    String redisKey= RedisKeyUtil.getTicketKey(ticket);
    LoginTicket loginTicket = (LoginTicket)redisTemplate.opsForValue().get(redisKey);
    loginTicket.setStatus(1);
    redisTemplate.opsForValue().set(redisKey,loginTicket);

}
public LoginTicket findLoginTicket(String ticket) {

    //return loginTicketMapper.selectLoginTicket(ticket);
    String redisKey= RedisKeyUtil.getTicketKey(ticket);
    LoginTicket loginTicket = (LoginTicket)redisTemplate.opsForValue().get(redisKey);
    return loginTicket;
}

Use Redis to cache user information

1. When querying, take priority from the cache;

2. Initialize the cached data when it cannot be retrieved from the cache;

3. Clear the cached data when the data is changed (if the method of updating the data in the cache is adopted, it may cause concurrency problems and be cumbersome);

Directly accessing the user object will be serialized into a Json string

 private static final String PREFIX_USER = "user";
// user
public static String getUserKey(int userId) {
    return PREFIX_USER + SPLIT + userId;
}
//1. When querying, take priority from the cache;
private User getCache(int userId)
{
    String redisKey=RedisKeyUtil.getUserLikeKey(userId);
    return  (User)redisTemplate.opsForValue().get(redisKey);

}

//2. Initialize the cached data when it cannot be retrieved from the cache;
private User initCache(int userId)
{
    User user=userMapper.queryById(userId);
    String redisKey=RedisKeyUtil.getUserLikeKey(userId);
    redisTemplate.opsForValue().set(redisKey,user,3600, TimeUnit.SECONDS);
    return user;
}

//3. Clear the cached data when the data is changed (if the method of updating the data in the cache is adopted, it may cause concurrency problems and be cumbersome);
private void clearCache(int userId)
{
    String redisKey=RedisKeyUtil.getUserLikeKey(userId);
    redisTemplate.delete(redisKey);
}
public User queryUserById(int userId) {
    //return userMapper.queryById(userId);
    User user=getCache(userId);
    if(user==null)
    {
        user=initCache(userId);
    }
    return  user;
}

Clean up the cache where the data is updated

//Update avatar path
public int updateHeader(int id,String header_url)
{
    //return userMapper.UpdateHeader(id,header_url);
    int rows=userMapper.UpdateHeader(id,header_url);
    clearCache(id);
    return rows;
}
  //Change the password. The password passed in here should be encrypted
    public int updatePassword(int id,String password)
    {
        int rows= userMapper.UpdatePassword(id,password);
        clearCache(id);
        return rows;
    }

Keywords: Java Redis Spring Boot Back-end

Added by metalhead41 on Sun, 06 Mar 2022 15:55:02 +0200