栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

秒杀系统1-登录功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

秒杀系统1-登录功能

学习目标

技术点

这里主要是秒杀业务,没有做前后端分离

如何设计一个秒杀系统

1、秒杀系统解决两个问题

  1. 并发读
  2. 并发写

2、秒杀系统的技术要求:

  1. 高性能
    秒杀涉及大量的并发读和并发写,因此支持高并发访问很重要,解决方案:动静分离、热点的发现与隔离、请求的削峰与分层过滤、服务端的极致优化。
  2. 一致性
    有限的商品被大量的请求 ,拍下减库存、付款减库存、预扣等几种扣库存的方式,在大并发下保证数据的准确性。
  3. 高可用
    避免出现考虑不到的情况,还有设计个planB方案,保证系统的高可用和正确性。
spring boot (java8)环境搭建

技术架构:springboot + mybatis-plus + mysql + thymeleaf
1、pom文件



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.0
         
    
    com.example
    seckill
    0.0.1-SNAPSHOT
    seckill
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.1
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    



2、application.yaml 配置文件
其中:使用 springboot默认的数据连接线程池:hikari(嘿卡瑞),号称最快的线程池

spring:
  # thymeleaf关闭缓存
  thymeleaf:
    cache: false

  # MySql数据源配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/secKill?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456

    # 最快的连接池
    hikari:
      # 连接池的名称
      pool-name: DateHikariCP
      # 最小空闲连接数
      minimum-idle: 5
      # 空闲连接存活最大时间 默认600000(10分钟)
      idle-timeout: 1800000
      # 最大连接数 默认10
      maximum-pool-size: 10
      # 从连接池返回的连接自动提交
      auto-commit: true
      # 连接最大存活时间  0代表永久存活,默认 1800000(分钟)
      max-lifetime: 1800000
      # 连接超时时间 默认30000(30秒)
      connection-timeout: 30000
      # 测试连接是否可以的查询语句
      connection-test-query: SELECt 1

# mybatis-plus 配置
mybatis-plus:
  # 配置 Mapper.xml的映射文件路径
  mapper-locations: classpath*:/mapper
@Component
public class MD5Util {

    // 加密使用的 --盐
    // 这个salt 和前端的盐进行统一
    private static final String salt = "1a2b3c4d";

    
    public static String md5(String src) {
        return DigestUtils.md5Hex(src);
    }

    // 第一次加密
    public static String inputPassToFromPass(String inputPass) {
        String str = salt.charAt(0) + salt.charAt(2) + inputPass + salt.charAt(5) + salt.charAt(4);
        return md5(str);
    }

    //

    
    public static String formPassToDBPass(String formPass, String salt) {
        String str = salt.charAt(0) + salt.charAt(2) + formPass + salt.charAt(5) + salt.charAt(4);
        return md5(str);
    }


    
    public static String inputPassToDBPass(String inputPass, String salt) {
        String fromPass = inputPassToFromPass(inputPass);
        String dbPass = formPassToDBPass(fromPass, salt);
        return dbPass;
    }



}

2、mybatis 的逆向工程

逆向工程

3、请求的返回

响应枚举类

package com.example.seckill.common;



public enum RespBeanEnum {

    //通用
    SUCCESS(200, "SUCCESS"),
    ERROR(500, "服务端异常"),

    //登录模块
    LOGIN_ERROR(500210, "用户名或者密码不正确"),
    MOBILE_ERROR(500211, "手机号码格式不正确"),
    BIND_ERROR(500212, "参数校验异常"),
    MOBILE_NOT_EXIST(500213, "手机号码不存在"),
    PASSWORD_UPDATE_FAIL(500214, "更新密码失败"),
    SESSION_ERROR(500215, "用户SESSION不存在"),


    //秒杀模块
    EMPTY_STOCK(500500, "库存不足"),
    REPEATE_ERROR(500501, "该商品每人限购一件"),
    REQUEST_ILLEGAL(500502, "请求非法,请重新尝试"),
    ERROR_CAPTCHA(500503, "验证码错误,请重新输入"),
    ACCESS_LIMIT_REACHED(500504, "访问过于频繁,请稍后重试"),
    //订单模块5003xx
    ORDER_NOT_EXIST(500300, "订单不存在"),


    ;

    private final Integer code;
    private final String message;

    public Integer getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    RespBeanEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

响应信息

package com.example.seckill.common;


public class RespBean {

    private long code;
    private String message;
    private Object object;

    public static RespBean success() {
        return new RespBean(RespBeanEnum.SUCCESS.getCode(), RespBeanEnum.SUCCESS.getMessage(), null);
    }

    public static RespBean success(Object object) {
        return new RespBean(RespBeanEnum.SUCCESS.getCode(), RespBeanEnum.SUCCESS.getMessage(), object);
    }

    public static RespBean error(RespBeanEnum respBeanEnum) {
        return new RespBean(respBeanEnum.getCode(), respBeanEnum.getMessage(), null);
    }

    public static RespBean error(RespBeanEnum respBeanEnum, Object object) {
        return new RespBean(respBeanEnum.getCode(), respBeanEnum.getMessage(), object);
    }

    public RespBean(long code, String message, Object object) {
        this.code = code;
        this.message = message;
        this.object = object;
    }

    public RespBean() {

    }

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getObject() {
        return object;
    }

    public void setObject(Object object) {
        this.object = object;
    }
}


3、跳转登录页面
@RequestMapping("/login")
@Controller
@Slf4j
public class LoginController {

    @RequestMapping ("toLogin")
    public String toLogin(){
        return "login";
    }


//    @PostMapping("/doLogin")
//    public String doLogin(){
//
//    }
}

登录页面与 登录的功能实现




    
    登录
    
    
    
    
    
    
    
    
    
    
    
    
    
    


用户登录

OKOKOOKOKOK

4、登录功能的实现

全局异常处理,以及 @NotNull等注解的使用

自定义校验手机号注解 @IsMobile

controller

    @RequestMapping("/doLogin")
    @ResponseBody
    public RespBean doLogin(@Valid LoginRequestParam param){

        log.info("{}",param);

        return userService.doLogin(param);
    }

参数

@Data
public class LoginRequestParam {

    @NotBlank(message = "mobile不能为空")
    @IsMobile
    private String mobile;

    @NotBlank(message = "password不能为空")
    @Length(min = 32,message = "password 长度不对")
    private String password;

}

service

@Service
public class UserServiceImpl extends ServiceImpl implements IUserService {
    @Autowired(required = false)
    UserMapper userMapper;


    @Override
    public RespBean doLogin(LoginRequestParam param) {
        String password = param.getPassword();
        String mobile = param.getMobile();

        User user = userMapper.selectById(mobile);
        if (null == user){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        if (!MD5Util.formPassToDBPass(password,user.getSalt()).equals(user.getPassword())){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);

        }
        return RespBean.success();
    }
}

由此可实现登录的异常处理


完善 登录功能,采用 cookie + session 记录用户信息 1、使用 uuid 工具类 创建 cookie 的值
package com.example.seckill.util;

import java.util.UUID;


public class UUIDUtil {
    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}

2、 cookie 工具类,对cookie进行操作
package com.example.seckill.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;


public final class CookieUtil {

    
    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        return getCookieValue(request, cookieName, false);
    }

    
    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    if (isDecoder) {
                        retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
                    } else {
                        retValue = cookieList[i].getValue();
                    }
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }

    
    public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }

    
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
                                 String cookieValue) {
        setCookie(request, response, cookieName, cookieValue, -1);
    }

    
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
                                 String cookieValue, int cookieMaxage) {
        setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
    }

    
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
                                 String cookieValue, boolean isEncode) {
        setCookie(request, response, cookieName, cookieValue, -1, isEncode);
    }

    
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
                                 String cookieValue, int cookieMaxage, boolean isEncode) {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
    }

    
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
                                 String cookieValue, int cookieMaxage, String encodeString) {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
    }

    
    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
                                    String cookieName) {
        doSetCookie(request, response, cookieName, "", -1, false);
    }

    
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
                                          String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else if (isEncode) {
                cookieValue = URLEncoder.encode(cookieValue, "utf-8");
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage > 0)
                cookie.setMaxAge(cookieMaxage);
            if (null != request) {// 设置域名的cookie
                String domainName = getDomainName(request);
                System.out.println(domainName);
                if (!"localhost".equals(domainName)) {
                    cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
                                          String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else {
                cookieValue = URLEncoder.encode(cookieValue, encodeString);
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage > 0) {
                cookie.setMaxAge(cookieMaxage);
            }
            if (null != request) {// 设置域名的cookie
                String domainName = getDomainName(request);
                System.out.println(domainName);
                if (!"localhost".equals(domainName)) {
                    cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    private static final String getDomainName(HttpServletRequest request) {
        String domainName = null;
        // 通过request对象获取访问的url地址
        String serverName = request.getRequestURL().toString();
        if (serverName == null || serverName.equals("")) {
            domainName = "";
        } else {
            // 将url地下转换为小写
            serverName = serverName.toLowerCase();
            // 如果url地址是以http://开头  将http://截取
            if (serverName.startsWith("http://")) {
                serverName = serverName.substring(7);
            }
            int end = serverName.length();
            // 判断url地址是否包含"/"
            if (serverName.contains("/")) {
                //得到第一个"/"出现的位置
                end = serverName.indexOf("/");
            }

            // 截取
            serverName = serverName.substring(0, end);
            // 根据"."进行分割
            final String[] domains = serverName.split("\.");
            int len = domains.length;
            if (len > 3) {
                // www.xxx.com.cn
                domainName = domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
            } else if (len <= 3 && len > 1) {
                // xxx.com or xxx.cn
                domainName = domains[len - 2] + "." + domains[len - 1];
            } else {
                domainName = serverName;
            }
        }

        if (domainName != null && domainName.indexOf(":") > 0) {
            String[] ary = domainName.split("\:");
            domainName = ary[0];
        }
        return domainName;
    }
}

3、校验用户成功后生成 cookie,将cookie 与用户存进 session中

这是就需要 controller 中加上 HttpServletRequest ,HttpServletResponse 两个入参

@RequestMapping("/doLogin")
    @ResponseBody
    public RespBean doLogin(@Valid LoginRequestParam param,HttpServletRequest request,HttpServletResponse response){

        log.info("{}",param);

        return userService.doLogin(param, request, response);
    }

在用户校验通过后

package com.example.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.seckill.common.RespBean;
import com.example.seckill.common.RespBeanEnum;
import com.example.seckill.controller.parm.LoginRequestParam;
import com.example.seckill.exception.GlobalException;
import com.example.seckill.mapper.UserMapper;
import com.example.seckill.pojo.User;
import com.example.seckill.service.IUserService;
import com.example.seckill.util.CookieUtil;
import com.example.seckill.util.MD5Util;
import com.example.seckill.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Service
public class UserServiceImpl extends ServiceImpl implements IUserService {
    @Autowired(required = false)
    UserMapper userMapper;


    @Override
    public RespBean doLogin(LoginRequestParam param, HttpServletRequest request, HttpServletResponse response) {
        String password = param.getPassword();
        String mobile = param.getMobile();

        User user = userMapper.selectById(mobile);
        if (null == user){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        if (!MD5Util.formPassToDBPass(password,user.getSalt()).equals(user.getPassword())){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        
        // 使用UUID生成 cookie
        String cookie = UUIDUtil.uuid();
        // 将 cookie 和用户存进 session 中
        request.getSession().setAttribute(cookie,user);
        // 设置 cookie
        CookieUtil.setCookie(request,response,"userCookie",cookie);


        return RespBean.success();
    }
}

此时点击登录会看到 cookie的值

4、goods Controller


因为登录成功会进行跳转商品列表页




    
    
    
    商品列表


package com.example.seckill.controller;

import com.example.seckill.common.RespBean;
import com.example.seckill.controller.parm.LoginRequestParam;
import com.example.seckill.pojo.User;
import com.example.seckill.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;


@RequestMapping("/goods")
@Controller
@Slf4j
public class GoodsController {

    @Autowired
    IGoodsService goodsService;


    
    @RequestMapping("/toList")
    public String toList(HttpSession session, Model model, @CookieValue("userCookie") String cookie){

        if (StringUtils.isEmpty(cookie)){ //如果 cookie为 空 跳转到 登录页面
            return "login";

        }
        // 从session 中获取用户
        User user = (User) session.getAttribute(cookie);

        if (null == user){ // 如果用户信息为空 跳转登录
            return "login";
        }
        // 将用户信息 传到前端页面
        model.addAttribute("user",user);
        return "goodsList";

    }

}

此时点击登录 会跳转页面

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/972422.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号