国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
1. Implement SMS login based on session
1.1 SMS login flow chart
1.2 Implementation of sending SMS verification code
3.1 Redis implements shared session login flow chart
Front-end request instructions:
Home Database Redis 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
redis session

1. Implement SMS login based on session

1.1 SMS login flow chart

How to implement SMS login in Redis shared session application

1.2 Implementation of sending SMS verification code

Front-end request instructions:

##InstructionsRequest methodPOSTRequest path/user/codeRequest parametersphone (phone number)Return valueNone

Back-end interface implementation:

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1. 校驗手機號
        if(RegexUtils.isPhoneInvalid(phone)){
            // 2. 如果不符合,返回錯誤信息
            return Result.fail("手機號格式錯誤!");
        }
        // 3. 符合,生成驗證碼(設(shè)置生成6位)
        String code = RandomUtil.randomNumbers(6);
        // 4. 保存驗證碼到 session
        session.setAttribute("code", code);
        // 5. 發(fā)送驗證碼(這里并未實現(xiàn),通過日志記錄)
        log.debug("發(fā)送短信驗證碼成功,驗證碼:{}", code);
        // 返回 ok
        return Result.ok();
    }
}

1.3 Implement SMS verification code login and registration

Front-end request instructions

DescriptionRequest methodPOSTRequest path/ user/loginRequest parametersphone (phone number); code (verification code)Return valueNone

Backend interface implementation:

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1. 校驗手機號
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            // 不一致,返回錯誤信息
            return Result.fail("手機號格式錯誤!");
        }
        // 2. 校驗驗證碼
        String cacheCode = (String) session.getAttribute("code");
        String code = loginForm.getCode();
        if(cacheCode == null || !cacheCode.equals(cacheCode)){
            // 不一致,返回錯誤信息
            return Result.fail("驗證碼錯誤!");
        }
        // 4. 一致,根據(jù)手機號查詢用戶(這里使用的 mybatis-plus)
        User user = query().eq("phone", phone).one();
        // 5. 判斷用戶是否存在
        if(user == null){
            // 6. 不存在,創(chuàng)建新用戶并保存
            user = createUserWithPhone(phone);
        }
        	// 7. 保存用戶信息到 session 中(通過 BeanUtil.copyProperties 方法將 user 中的信息過濾到 UserDTO 上,即用來隱藏部分信息)
        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        return Result.ok();
    }

    private User createUserWithPhone(String phone) {
        // 1. 創(chuàng)建用戶
        User user = new User();
        user.setPhone(phone);
        user.setNickName("user_" + RandomUtil.randomString(10));
        // 2. 保存用戶(這里使用 mybatis-plus)
        save(user);
        return user;
    }
}

1.4 Implement login verification interceptor

Login verification interceptor Implementation:

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 獲取 session
        HttpSession session = request.getSession();
        // 2. 獲取 session 中的用戶
        UserDTO user = (UserDTO) session.getAttribute("user");
        // 3. 判斷用戶是否存在
        if(user == null){
            // 4. 不存在,攔截,返回 401 未授權(quán)
            response.setStatus(401);
            return false;
        }
        // 5. 存在,保存用戶信息到 ThreadLocal
        UserHolder.saveUser(user);
        // 6. 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用戶,避免內(nèi)存泄露
        UserHolder.removeUser();
    }
}

UserHolder class implementation: This class defines a static ThreadLocal

public class UserHolder {
    private static final ThreadLocal<UserDTO> tl = new ThreadLocal<>();

    public static void saveUser(UserDTO user){
        tl.set(user);
    }

    public static UserDTO getUser(){
        return tl.get();
    }

    public static void removeUser(){
        tl.remove();
    }
}

Configuration interceptor:

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns(
                        "/user/login",
                        "/user/code"
                );
    }
}

Front-end request description:

DescriptionRequest methodPOSTRequest path/user/meRequest parametersNoneReturn value None

Backend interface implementation:

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result me() {
        UserDTO user = UserHolder.getUser();
        return Result.ok(user);
    }
}

2. Cluster session sharing problem

session sharing problem :

Multiple tomcats do not share session storage space. When the request is switched to different tomcat services, it will cause data loss.

Session alternatives should meet the following conditions:

  • Data sharing (different tomcats can access data in Redis)

  • Memory storage (Redis stores through memory)

  • key, value structure (Redis is a key-value structure)

3. Based on Redis implements shared session login

3.1 Redis implements shared session login flow chart

How to implement SMS login in Redis shared session application

How to implement SMS login in Redis shared session application##3.2 Implement sending SMS verification code

Front-end request instructions:

Request methodRequest pathRequest parametersReturn value Backend interface implementation :

Instructions
POST
/user/code
phone(phone number)
None
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1. 校驗手機號
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2. 如果不符合,返回錯誤信息
            return Result.fail("手機號格式錯誤!");
        }
        // 3. 符合,生成驗證碼(設(shè)置生成6位)
        String code = RandomUtil.randomNumbers(6);
        // 4. 保存驗證碼到 Redis(以手機號為 key,設(shè)置有效期為 2min)
        stringRedisTemplate.opsForValue().set("login:code:" + phone, code, 2, TimeUnit.MINUTES);
        // 5. 發(fā)送驗證碼(這里并未實現(xiàn),通過日志記錄)
        log.debug("發(fā)送短信驗證碼成功,驗證碼:{}", code);
        // 返回 ok
        return Result.ok();
    }
}

3.3 Implement SMS verification code login and registration

Front-end request instructions:

Request methodRequest pathRequest parameters##Return valueNoneBackend interface implementation:
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1. 校驗手機號
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            // 不一致,返回錯誤信息
            return Result.fail("手機號格式錯誤!");
        }
        // 2. 校驗驗證碼
        String cacheCode = (String) session.getAttribute("code");
        String code = loginForm.getCode();
        if(cacheCode == null || !cacheCode.equals(cacheCode)){
            // 不一致,返回錯誤信息
            return Result.fail("驗證碼錯誤!");
        }
        // 4. 一致,根據(jù)手機號查詢用戶(這里使用的 mybatis-plus)
        User user = query().eq("phone", phone).one();
        // 5. 判斷用戶是否存在
        if(user == null){
            // 6. 不存在,創(chuàng)建新用戶并保存
            user = createUserWithPhone(phone);
        }
        	// 7. 保存用戶信息到 session 中(通過 BeanUtil.copyProperties 方法將 user 中的信息過濾到 UserDTO 上,即用來隱藏部分信息)
        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        return Result.ok();
    }

    private User createUserWithPhone(String phone) {
        // 1. 創(chuàng)建用戶
        User user = new User();
        user.setPhone(phone);
        user.setNickName("user_" + RandomUtil.randomString(10));
        // 2. 保存用戶(這里使用 mybatis-plus)
        save(user);
        return user;
    }
}

Description
POST
/user/login
phone (phone number); code (verification code)
3.4 Implement login verification interceptor

Here the original interceptor is divided into two interceptors The first interceptor intercepts all requests. Each interception refreshes the validity period of the token and saves the user information that can be queried into ThreadLocal. The second interceptor performs the interception function and intercepts the path that requires login.

Refresh token interceptor implementation:

public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 獲取請求頭中的 token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            return true;
        }
        // 2. 基于 token 獲取 redis 中的用戶
        String tokenKey = "login:token:" + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
        // 3. 判斷用戶是否存在
        if (userMap.isEmpty()) {
            return true;
        }
        // 5. 將查詢到的 Hash 數(shù)據(jù)轉(zhuǎn)為 UserDTO 對象
        UserDTO user = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        // 6. 存在,保存用戶信息到 ThreadLocal
        UserHolder.saveUser(user);
        // 7. 刷新 token 有效期 30 min
        stringRedisTemplate.expire(tokenKey, 30, TimeUnit.MINUTES);
        // 8. 放行
        return true;
    }
}

Login verification interceptor implementation:

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 獲取 session
        HttpSession session = request.getSession();
        // 2. 獲取 session 中的用戶
        UserDTO user = (UserDTO) session.getAttribute("user");
        // 3. 判斷用戶是否存在
        if(user == null){
            // 4. 不存在,攔截,返回 401 未授權(quán)
            response.setStatus(401);
            return false;
        }
        // 5. 存在,保存用戶信息到 ThreadLocal
        UserHolder.saveUser(user);
        // 6. 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用戶,避免內(nèi)存泄露
        UserHolder.removeUser();
    }
}

UserHolder class implementation: This class defines a static ThreadLocal

public class UserHolder {
    private static final ThreadLocal<UserDTO> tl = new ThreadLocal<>();

    public static void saveUser(UserDTO user){
        tl.set(user);
    }

    public static UserDTO getUser(){
        return tl.get();
    }

    public static void removeUser(){
        tl.remove();
    }
}

Configure interceptor:

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RefreshTokenInterceptor(stringRedisTemplate))
                .addPathPatterns("/**").order(0);
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns(
                        "/user/login",
                        "/user/code"
                ).order(1);
    }
}

Front-end request description:

Request methodPOSTRequest path/user/meRequest parametersNoneReturn valueNone Backend interface implementation :
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result me() {
        UserDTO user = UserHolder.getUser();
        return Result.ok(user);
    }
}

The above is the detailed content of How to implement SMS login in Redis shared session application. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Laravel8 optimization points Laravel8 optimization points Apr 18, 2025 pm 12:24 PM

Laravel 8 provides the following options for performance optimization: Cache configuration: Use Redis to cache drivers, cache facades, cache views, and page snippets. Database optimization: establish indexing, use query scope, and use Eloquent relationships. JavaScript and CSS optimization: Use version control, merge and shrink assets, use CDN. Code optimization: Use Composer installation package, use Laravel helper functions, and follow PSR standards. Monitoring and analysis: Use Laravel Scout, use Telescope, monitor application metrics.

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot? What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot? Apr 19, 2025 pm 08:03 PM

In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

Recommended Laravel's best expansion packs: 2024 essential tools Recommended Laravel's best expansion packs: 2024 essential tools Apr 30, 2025 pm 02:18 PM

The essential Laravel extension packages for 2024 include: 1. LaravelDebugbar, used to monitor and debug code; 2. LaravelTelescope, providing detailed application monitoring; 3. LaravelHorizon, managing Redis queue tasks. These expansion packs can improve development efficiency and application performance.

Laravel environment construction and basic configuration (Windows/Mac/Linux) Laravel environment construction and basic configuration (Windows/Mac/Linux) Apr 30, 2025 pm 02:27 PM

The steps to build a Laravel environment on different operating systems are as follows: 1.Windows: Use XAMPP to install PHP and Composer, configure environment variables, and install Laravel. 2.Mac: Use Homebrew to install PHP and Composer and install Laravel. 3.Linux: Use Ubuntu to update the system, install PHP and Composer, and install Laravel. The specific commands and paths of each system are different, but the core steps are consistent to ensure the smooth construction of the Laravel development environment.

Redis's Role: Exploring the Data Storage and Management Capabilities Redis's Role: Exploring the Data Storage and Management Capabilities Apr 22, 2025 am 12:10 AM

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

In a multi-node environment, how to ensure that Spring Boot's @Scheduled timing task is executed only on one node? In a multi-node environment, how to ensure that Spring Boot's @Scheduled timing task is executed only on one node? Apr 19, 2025 pm 10:57 PM

The optimization solution for SpringBoot timing tasks in a multi-node environment is developing Spring...

Redis: Understanding Its Architecture and Purpose Redis: Understanding Its Architecture and Purpose Apr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

See all articles
    Description
  • <del id="ucesw"><sup id="ucesw"></sup></del>
  • <ul id="ucesw"><sup id="ucesw"></sup></ul>
    • <abbr id="ucesw"><sup id="ucesw"></sup></abbr>