SpringBoot自定义注解实现身份证号格式校验

该博客介绍了一种在Spring Boot应用中利用AOP进行身份证格式校验的方法,包括引入Spring AOP依赖,创建注解和切面处理类。身份证号被解密后进行格式校验,通过IdcardValidator类进行15位和18位身份证的合法性验证,包括出生日期、性别、地区等信息。此外,还展示了如何通过注解配置解密敏感数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

​ 身份证的组成部分较为复杂, 如果仅使用正则表达式的话, 有些情况也无法校验出来, 例如正确的证件号为513334200310119074, 如果把最后一位变成9, 则是一个错误的证件号, 但正则依旧可以校验通过; 如果我们想更加精准的校验身份证格式需要一些额外处理;

代码实现

pom依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

只需要引入这个依赖就可以了

Springboot启动类:

@EnableAspectJAutoProxy

启动类上额外新加一个注解

注解类:

package com.joy.real.annotation;

import org.springframework.core.annotation.AliasFor;

import java.lang.annotation.*;

/**
 * @Description: 证件号格式校验注解
 * @packe: com.joy.real.annotation
 * @author: cao taibai
 * @date: 2021/5/14 9:40
 */

@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface IdCardValid {

    // 是否需要解密
    @AliasFor("value")
    boolean isDecrypt() default false;

    @AliasFor("isDecrypt")
    boolean value() default false;
}

这里的两个属性 isDecrypt 与value的是一样, 使用@AliasFor注解后, 可以让我们在使用注解时不需要写参数名(@IdCardValid(true))

PS: 在我们单位中身份证号属于敏感数据, 交互以及入库时需要加密, 所以这里我加了一个解密的boolean

AOP类:

package com.joy.real.aop;

import com.alibaba.fastjson.JSONObject;
import com.joy.error.JoyException;
import com.joy.real.annotation.IdCardValid;
import com.joy.real.utils.AesUtil;
import com.joy.real.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Description: 身份证号格式校验AOP
 * @packe: com.joy.real.aop
 * @author: cao taibai
 * @date: 2021/5/14 9:48
 */
@Slf4j
@Aspect
@Component
public class IdCardFormatCheckAspect {

    // aes加解密key
    public static String aesSecretKey;


    @Pointcut("@annotation(com.joy.real.annotation.IdCardValid)")
    public void idCardAnnotationPoint() {
    }

    @Before("idCardAnnotationPoint() && @annotation(idCardValid)")
    public void before(JoinPoint joinPoint, IdCardValid idCardValid) {
        // 遍历参数
        for (Object args : joinPoint.getArgs()) {

            // 解析
            JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(args));
            String cardNo = json.getString("cardNo");

            // 如果不存在cardNo就放弃
            if (StringUtils.isEmpty(cardNo)) {
                continue;
            }

            // 获取注解的属性值
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            IdCardValid annotation = methodSignature.getMethod().getAnnotation(IdCardValid.class);

            // 如果为true则解密
            if (annotation.value()) {
                // 解密
                cardNo = AesUtil.aesDecrypt(cardNo, aesSecretKey);
            }

            // 校验格式
            IdcardValidator idcardValidator = new IdcardValidator();
            boolean result = idcardValidator.isValidatedAllIdcard(cardNo);
            if (!result) {
                log.error("[ 身份证号格式校验 ] 证件号 [ {} ] 格式错误", cardNo);
                throw new JoyException("RZ1048");
            }
        }

    }


    @Value("${joy.real.data.aes.key}")
    public void setAesSecretKey(String aesSecretKey) {
        IdCardFormatCheckAspect.aesSecretKey = aesSecretKey;
    }
}

可以将cardNo这个参数名字当作注解属性, 然后json.getString(“cardNo”)时会更灵活些

身份证格式校验类:

package com.joy.real.utils;

import lombok.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Pattern;

/**
 * @Description:
 * @packe: com.joy.real.annon
 * @author: cao taibai
 * @date: 2021/5/13 17:22
 */

@Getter
@Setter
@ToString
@Builder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
public class IdcardValidator {
    /**
     * 省,直辖市代码表: { 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",
     * 21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",
     * 33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",
     * 42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",
     * 51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",
     * 63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}
     */
    protected String codeAndCity[][] = { { "11", "北京" }, { "12", "天津" },
            { "13", "河北" }, { "14", "山西" }, { "15", "内蒙古" }, { "21", "辽宁" },
            { "22", "吉林" }, { "23", "黑龙江" }, { "31", "上海" }, { "32", "江苏" },
            { "33", "浙江" }, { "34", "安徽" }, { "35", "福建" }, { "36", "江西" },
            { "37", "山东" }, { "41", "河南" }, { "42", "湖北" }, { "43", "湖南" },
            { "44", "广东" }, { "45", "广西" }, { "46", "海南" }, { "50", "重庆" },
            { "51", "四川" }, { "52", "贵州" }, { "53", "云南" }, { "54", "西藏" },
            { "61", "陕西" }, { "62", "甘肃" }, { "63", "青海" }, { "64", "宁夏" },
            { "65", "新疆" }, { "71", "台湾" }, { "81", "香港" }, { "82", "澳门" },
            { "91", "国外" } };

    private String cityCode[] = { "11", "12", "13", "14", "15", "21", "22",
            "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43",
            "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63",
            "64", "65", "71", "81", "82", "91" };

    // 每位加权因子
    private int power[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };

    // 第18位校检码
    private String verifyCode[] = { "1", "0", "X", "9", "8", "7", "6", "5",
            "4", "3", "2" };

    /**
     * 验证所有的身份证的合法性
     *
     * @param idcard
     * @return
     */
    public boolean isValidatedAllIdcard(String idcard) {
        if (idcard.length() == 15) {
            idcard = this.convertIdcarBy15bit(idcard);
        }
        return this.isValidate18Idcard(idcard);
    }

    /**
     * <p>
     * 判断18位身份证的合法性
     * </p>
     * 根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。
     * 排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。
     * <p>
     * 顺序码: 表示在同一地址码所标识的区域范围内,对同年、同月、同 日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配 给女性。
     * </p>
     * <p>
     * 1.前1、2位数字表示:所在省份的代码; 2.第3、4位数字表示:所在城市的代码; 3.第5、6位数字表示:所在区县的代码;
     * 4.第7~14位数字表示:出生年、月、日; 5.第15、16位数字表示:所在地的派出所的代码;
     * 6.第17位数字表示性别:奇数表示男性,偶数表示女性;
     * 7.第18位数字是校检码:也有的说是个人信息码,一般是随计算机的随机产生,用来检验身份证的正确性。校检码可以是0~9的数字,有时也用x表示。
     * </p>
     * <p>
     * 第十八位数字(校验码)的计算方法为: 1.将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4
     * 2 1 6 3 7 9 10 5 8 4 2
     * </p>
     * <p>
     * 2.将这17位数字和系数相乘的结果相加。
     * </p>
     * <p>
     * 3.用加出来和除以11,看余数是多少?
     * </p>
     * 4.余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3
     * 2。
     * <p>
     * 5.通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10,身份证的最后一位号码就是2。
     * </p>
     *
     * @param idcard
     * @return
     */
    public boolean isValidate18Idcard(String idcard) {
        // 非18位为假
        if (idcard.length() != 18) {
            return false;
        }
        // 获取前17位
        String idcard17 = idcard.substring(0, 17);
        // 获取第18位
        String idcard18Code = idcard.substring(17, 18);
        char c[] = null;
        String checkCode = "";
        // 是否都为数字
        if (isDigital(idcard17)) {
            c = idcard17.toCharArray();
        } else {
            return false;
        }

        if (null != c) {
            int bit[] = new int[idcard17.length()];

            bit = converCharToInt(c);

            int sum17 = 0;

            sum17 = getPowerSum(bit);

            // 将和值与11取模得到余数进行校验码判断
            checkCode = getCheckCodeBySum(sum17);
            if (null == checkCode) {
                return false;
            }
            // 将身份证的第18位与算出来的校码进行匹配,不相等就为假
            if (!idcard18Code.equalsIgnoreCase(checkCode)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 验证15位身份证的合法性,该方法验证不准确,最好是将15转为18位后再判断,该类中已提供。
     *
     * @param idcard
     * @return
     */
    public boolean isValidate15Idcard(String idcard) {
        // 非15位为假
        if (idcard.length() != 15) {
            return false;
        }

        // 是否全都为数字
        if (isDigital(idcard)) {
            String provinceid = idcard.substring(0, 2);
            String birthday = idcard.substring(6, 12);
            int year = Integer.parseInt(idcard.substring(6, 8));
            int month = Integer.parseInt(idcard.substring(8, 10));
            int day = Integer.parseInt(idcard.substring(10, 12));

            // 判断是否为合法的省份
            boolean flag = false;
            for (String id : cityCode) {
                if (id.equals(provinceid)) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                return false;
            }
            // 该身份证生出日期在当前日期之后时为假
            Date birthdate = null;
            try {
                birthdate = new SimpleDateFormat("yyMMdd").parse(birthday);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (birthdate == null || new Date().before(birthdate)) {
                return false;
            }

            // 判断是否为合法的年份
            GregorianCalendar curDay = new GregorianCalendar();
            int curYear = curDay.get(Calendar.YEAR);
            int year2bit = Integer.parseInt(String.valueOf(curYear)
                    .substring(2));

            // 判断该年份的两位表示法,小于50的和大于当前年份的,为假
            if ((year < 50 && year > year2bit)) {
                return false;
            }

            // 判断是否为合法的月份
            if (month < 1 || month > 12) {
                return false;
            }

            // 判断是否为合法的日期
            boolean mflag = false;
            curDay.setTime(birthdate); // 将该身份证的出生日期赋于对象curDay
            switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    mflag = (day >= 1 && day <= 31);
                    break;
                case 2: // 公历的2月非闰年有28天,闰年的2月是29天。
                    if (curDay.isLeapYear(curDay.get(Calendar.YEAR))) {
                        mflag = (day >= 1 && day <= 29);
                    } else {
                        mflag = (day >= 1 && day <= 28);
                    }
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    mflag = (day >= 1 && day <= 30);
                    break;
            }
            if (!mflag) {
                return false;
            }
        } else {
            return false;
        }
        return true;
    }

    /**
     * 将15位的身份证转成18位身份证
     *
     * @param idcard
     * @return
     */
    public String convertIdcarBy15bit(String idcard) {
        String idcard17 = null;
        // 非15位身份证
        if (idcard.length() != 15) {
            return null;
        }

        if (isDigital(idcard)) {
            // 获取出生年月日
            String birthday = idcard.substring(6, 12);
            Date birthdate = null;
            try {
                birthdate = new SimpleDateFormat("yyMMdd").parse(birthday);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Calendar cday = Calendar.getInstance();
            cday.setTime(birthdate);
            String year = String.valueOf(cday.get(Calendar.YEAR));

            idcard17 = idcard.substring(0, 6) + year + idcard.substring(8);

            char c[] = idcard17.toCharArray();
            String checkCode = "";

            if (null != c) {
                int bit[] = new int[idcard17.length()];

                // 将字符数组转为整型数组
                bit = converCharToInt(c);
                int sum17 = 0;
                sum17 = getPowerSum(bit);

                // 获取和值与11取模得到余数进行校验码
                checkCode = getCheckCodeBySum(sum17);
                // 获取不到校验位
                if (null == checkCode) {
                    return null;
                }

                // 将前17位与第18位校验码拼接
                idcard17 += checkCode;
            }
        } else { // 身份证包含数字
            return null;
        }
        return idcard17;
    }

    /**
     * 15位和18位身份证号码的基本数字和位数验校
     *
     * @param idcard
     * @return
     */
    public boolean isIdcard(String idcard) {
        return idcard == null || "".equals(idcard) ? false : Pattern.matches(
                "(^\\d{15}$)|(\\d{17}(?:\\d|x|X)$)", idcard);
    }

    /**
     * 15位身份证号码的基本数字和位数验校
     *
     * @param idcard
     * @return
     */
    public boolean is15Idcard(String idcard) {
        return idcard == null || "".equals(idcard) ? false : Pattern.matches(
                "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$",
                idcard);
    }

    /**
     * 18位身份证号码的基本数字和位数验校
     *
     * @param idcard
     * @return
     */
    public boolean is18Idcard(String idcard) {
        return Pattern
                .matches(
                        "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([\\d|x|X]{1})$",
                        idcard);
    }

    /**
     * 数字验证
     *
     * @param str
     * @return
     */
    public boolean isDigital(String str) {
        return str == null || "".equals(str) ? false : str.matches("^[0-9]*$");
    }

    /**
     * 将身份证的每位和对应位的加权因子相乘之后,再得到和值
     *
     * @param bit
     * @return
     */
    public int getPowerSum(int[] bit) {

        int sum = 0;

        if (power.length != bit.length) {
            return sum;
        }

        for (int i = 0; i < bit.length; i++) {
            for (int j = 0; j < power.length; j++) {
                if (i == j) {
                    sum = sum + bit[i] * power[j];
                }
            }
        }
        return sum;
    }

    /**
     * 将和值与11取模得到余数进行校验码判断
     *
     * @param sum17
     * @param sum17
     * @return 校验位
     */
    public String getCheckCodeBySum(int sum17) {
        String checkCode = null;
        switch (sum17 % 11) {
            case 10:
                checkCode = "2";
                break;
            case 9:
                checkCode = "3";
                break;
            case 8:
                checkCode = "4";
                break;
            case 7:
                checkCode = "5";
                break;
            case 6:
                checkCode = "6";
                break;
            case 5:
                checkCode = "7";
                break;
            case 4:
                checkCode = "8";
                break;
            case 3:
                checkCode = "9";
                break;
            case 2:
                checkCode = "x";
                break;
            case 1:
                checkCode = "0";
                break;
            case 0:
                checkCode = "1";
                break;
        }
        return checkCode;
    }

    /**
     * 将字符数组转为整型数组
     *
     * @param c
     * @return
     * @throws NumberFormatException
     */
    public int[] converCharToInt(char[] c) throws NumberFormatException {
        int[] a = new int[c.length];
        int k = 0;
        for (char temp : c) {
            a[k++] = Integer.parseInt(String.valueOf(temp));
        }
        return a;
    }
}
package com.joy.real.utils;

import lombok.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description:
 * @packe: com.joy.real.annon
 * @author: cao taibai
 * @date: 2021/5/13 17:23
 */
@Getter
@Setter
@ToString
@Builder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
public class IdcardInfoExtractor {
    // 省份
    private String province;
    // 城市
    private String city;
    // 区县
    private String region;
    // 年份
    private int year;
    // 月份
    private int month;
    // 日期
    private int day;
    // 性别
    private String gender;
    // 出生日期
    private Date birthday;

    private Map<String, String> cityCodeMap = new HashMap<String, String>() {
        {
            this.put("11", "北京");
            this.put("12", "天津");
            this.put("13", "河北");
            this.put("14", "山西");
            this.put("15", "内蒙古");
            this.put("21", "辽宁");
            this.put("22", "吉林");
            this.put("23", "黑龙江");
            this.put("31", "上海");
            this.put("32", "江苏");
            this.put("33", "浙江");
            this.put("34", "安徽");
            this.put("35", "福建");
            this.put("36", "江西");
            this.put("37", "山东");
            this.put("41", "河南");
            this.put("42", "湖北");
            this.put("43", "湖南");
            this.put("44", "广东");
            this.put("45", "广西");
            this.put("46", "海南");
            this.put("50", "重庆");
            this.put("51", "四川");
            this.put("52", "贵州");
            this.put("53", "云南");
            this.put("54", "西藏");
            this.put("61", "陕西");
            this.put("62", "甘肃");
            this.put("63", "青海");
            this.put("64", "宁夏");
            this.put("65", "新疆");
            this.put("71", "台湾");
            this.put("81", "香港");
            this.put("82", "澳门");
            this.put("91", "国外");
        }
    };

    private IdcardValidator validator = null;

    /**
     * 通过构造方法初始化各个成员属性
     */
    public IdcardInfoExtractor(String idcard) {
        try {
            validator = new IdcardValidator();
            if (validator.isValidatedAllIdcard(idcard)) {
                if (idcard.length() == 15) {
                    idcard = validator.convertIdcarBy15bit(idcard);
                }
                // 获取省份
                String provinceId = idcard.substring(0, 2);
                Set<String> key = this.cityCodeMap.keySet();
                for (String id : key) {
                    if (id.equals(provinceId)) {
                        this.province = this.cityCodeMap.get(id);
                        break;
                    }
                }

                // 获取性别
                String id17 = idcard.substring(16, 17);
                if (Integer.parseInt(id17) % 2 != 0) {
                    this.gender = "男";
                } else {
                    this.gender = "女";
                }

                // 获取出生日期
                String birthday = idcard.substring(6, 14);
                Date birthdate = new SimpleDateFormat("yyyyMMdd")
                        .parse(birthday);
                this.birthday = birthdate;
                GregorianCalendar currentDay = new GregorianCalendar();
                currentDay.setTime(birthdate);
                this.year = currentDay.get(Calendar.YEAR);
                this.month = currentDay.get(Calendar.MONTH) + 1;
                this.day = currentDay.get(Calendar.DAY_OF_MONTH);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

参考: https://www.jianshu.com/p/c9c165d2732d

测试

接下来使用513334200310119074和513334200310119079来测试下

调用:

	/**
     *  RZ-031 实名认证明细分页查询
     * @param rz_031_req
     * @return
     * @throws JoyException
     */
    @IdCardValid(true)
    @ResponseBody
    @RequestMapping("/RZ-031")
    public ResponseBean RZ_013(@Valid @RequestBody RZ_031_Req rz_031_req) throws JoyException{
        return doRealBusiness(rz_031_req, "RZ-031");
    }

513334200310119074测试结果:
我们期望得到一个正确结果

513334200310119079测试结果:
我们期望得到一个格式错误得结果

完美~!

<think>好的,我现在需要处理用户的问题:使用Spring Boot和MyBatis-Plus创建一个能够处理多线程并发请求、防止重复数据的生产级接口。用户还提供了一个JSON示例,我需要根据这个结构来设计接口。 首先,我得理清用户的需求。用户希望一个POST接口,接收给定的JSON格式数据,处理时需要考虑高并发和重复数据的问题。作为生产环境代码,必须考虑线程安全、数据一致性和性能优化。 接下来,分析可能的问题点。多线程环境下,重复数据提交是一个关键点。如何防止重复?通常可以采用数据库唯一索引、分布式锁或者业务层校验。这里需要结合MyBatis-Plus的特性来实现。 首先设计数据表结构。根据JSON结构,主表是展览信息,从表是门票列表。需要将这两个实体映射到数据库表中。主表可能有exhibition_id作为主键,从表的ticket_id为主键,同时需要确保同一card_no在同一个exhibition下唯一,避免重复插入。因此,在从表中设置唯一索引(exhibition_id, card_no)是必要的。 然后是实体类的设计。使用MyBatis-Plus需要定义对应的实体类,主表Exhibition和从表Ticket。注意使用注解如@TableId指定主键,@TableField映射字段名。 接下来是DAO层,即Mapper接口。继承MyBatis-Plus的BaseMapper,获得基本的CRUD操作。对于批量插入门票,可能需要自定义方法,使用SQL的INSERT IGNORE或ON DUPLICATE KEY UPDATE来处理重复数据。 服务层的设计需要考虑事务管理和并发控制。处理主表和从表的数据插入需要放在一个事务中,保证原子性。对于高并发,可以使用分布式锁,比如Redis的Redisson来实现,防止多个线程同时处理同一请求导致数据重复。同时,使用@Transactional注解确保事务的完整性。 控制层接收JSON请求,将其映射到DTO对象。这里需要定义两个DTO:ExhibitionRequestDTO和TicketDTO,结构对应JSON的层次。使用@RequestBody接收POST请求的数据。 在插入门票数据时,需要注意批量操作的效率。MyBatis-Plus的saveBatch方法默认是逐条插入,这在生产环境中效率不高。需要配置批量插入的SQL会话,启用批处理模式,比如在配置文件中设置jdbc-url添加rewriteBatchedStatements=true,并在MyBatisPlusConfig中配置性能分析插件,设置批量操作的参数。 防止重复数据的策略包括数据库唯一索引和业务逻辑校验。唯一索引是最可靠的,即使应用层有漏洞,数据库层也能拦截重复数据。业务层可以在插入前查询是否存在,但高并发下可能失效,因此需要结合分布式锁。例如,在插入前获取一个基于exhibitionId和cardNo的锁,确保同一时间只有一个线程处理相同的数据。 异常处理方面,需要捕获唯一约束冲突的异常,比如DuplicateKeyException,并返回友好的错误信息,而不是让服务器抛出500错误。同时,事务管理要确保在发生异常时回滚,避免脏数据。 测试方面,需要考虑使用JMeter或Postman进行压力测试,模拟多线程请求,验证接口的并发处理能力和重复数据拦截效果。确保在高并发下,系统响应时间和资源消耗在可接受范围内。 最后,代码的健壮性和可维护性需要考虑日志记录、参数校验、全局异常处理等。例如,使用@Valid对DTO进行校验,确保传入参数符合要求,减少非法数据的处理。 可能遇到的问题包括:MyBatis-Plus批量插入的性能问题,需要正确配置;分布式锁的实现需要考虑锁的粒度和超时时间,避免死锁;事务的传播机制和隔离级别需要合理设置,防止脏读或不可重复读。 总结步骤:设计数据库表和唯一索引→创建实体类和DTO→编写Mapper接口和自定义批量插入方法→实现服务层,添加分布式锁和事务→配置MyBatis-Plus批量处理→编写控制器→异常处理和日志→测试验证。</think>我将基于Spring Boot + MyBatis-Plus实现一个生产级的高并发接口,包含以下核心设计: 1. 数据库设计(MySQL示例): ```sql -- 主表 CREATE TABLE exhibition_info ( id BIGINT PRIMARY KEY COMMENT '主键ID', exhibition_id VARCHAR(32) NOT NULL COMMENT '展览ID', exhibition_id_type CHAR(1) NOT NULL COMMENT '展览ID类型', source_from VARCHAR(32) NOT NULL COMMENT '来源', UNIQUE KEY idx_exhibition_id (exhibition_id) ); -- 门票表 CREATE TABLE ticket_info ( ticket_id BIGINT PRIMARY KEY COMMENT '主键ID', exhibition_id VARCHAR(32) NOT NULL COMMENT '展览ID', card_no VARCHAR(64) NOT NULL COMMENT '卡号', face_status CHAR(1) NOT NULL COMMENT '人脸状态', id_number VARCHAR(32) NOT NULL COMMENT '身份证号', name VARCHAR(64) NOT NULL COMMENT '姓名', number_type CHAR(1) NOT NULL COMMENT '号码类型', ticket_status CHAR(1) NOT NULL COMMENT '门票状态', ticket_type_name VARCHAR(32) NOT NULL COMMENT '票种名称', UNIQUE KEY idx_exhibition_card (exhibition_id, card_no) ); ``` 2. 实体类: ```java // ExhibitionInfo.java @Data @TableName("exhibition_info") public class ExhibitionInfo { @TableId(value = "id", type = IdType.ASSIGN_ID) private Long id; private String exhibitionId; private String exhibitionIdType; private String sourceFrom; } // TicketInfo.java @Data @TableName("ticket_info") public class TicketInfo { @TableId(value = "ticket_id", type = IdType.ASSIGN_ID) private Long ticketId; private String exhibitionId; private String cardNo; private String faceStatus; private String idNumber; private String name; private String numberType; private String ticketStatus; private String ticketTypeName; } ``` 3. Mapper接口: ```java public interface TicketMapper extends BaseMapper<TicketInfo> { @Insert("<script>" + "INSERT IGNORE INTO ticket_info " + "(exhibition_id, card_no, face_status, id_number, name, number_type, ticket_status, ticket_type_name) " + "VALUES " + "<foreach collection='list' item='item' separator=','>" + "(#{item.exhibitionId}, #{item.cardNo}, #{item.faceStatus}, #{item.idNumber}, " + "#{item.name}, #{item.numberType}, #{item.ticketStatus}, #{item.ticketTypeName})" + "</foreach>" + "</script>") int batchInsertIgnore(@Param("list") List<TicketInfo> list); } ``` 4. Service层: ```java @Service @RequiredArgsConstructor public class ExhibitionService { private final RedissonClient redissonClient; private final ExhibitionInfoMapper exhibitionInfoMapper; private final TicketMapper ticketMapper; @Transactional(rollbackFor = Exception.class) public void processExhibition(ExhibitionRequestDTO dto) { // 处理主表 ExhibitionInfo exhibition = new ExhibitionInfo(); BeanUtils.copyProperties(dto, exhibition); exhibitionInfoMapper.insertOrUpdate(exhibition); // 分布式锁防止重复提交 RLock lock = redissonClient.getLock("EXHIBITION_LOCK:" + dto.getExhibitionId()); try { if (lock.tryLock(3, 5, TimeUnit.SECONDS)) { // 处理票务数据 List<TicketInfo> tickets = dto.getTicketList().stream().map(t -> { TicketInfo info = new TicketInfo(); BeanUtils.copyProperties(t, info); info.setExhibitionId(dto.getExhibitionId()); return info; }).collect(Collectors.toList()); // 批量插入(忽略重复) ticketMapper.batchInsertIgnore(tickets); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("获取锁失败", e); } finally { if (lock.isHeldByCurrentThread()) { lock.unlock(); } } } } ``` 5. Controller层: ```java @RestController @RequiredArgsConstructor public class ExhibitionController { private final ExhibitionService exhibitionService; @PostMapping("/api/exhibition") public ResponseEntity<?> createExhibition(@Valid @RequestBody ExhibitionRequestDTO dto) { try { exhibitionService.processExhibition(dto); return ResponseEntity.ok().build(); } catch (DuplicateKeyException e) { return ResponseEntity.status(HttpStatus.CONFLICT) .body(Result.error("数据重复提交")); } } } // DTO类 @Data public class ExhibitionRequestDTO { @NotBlank private String exhibitionId; @NotBlank @Pattern(regexp = "[0-1]") private String exhibitionIdType; @NotBlank private String sourceFrom; @Valid @NotEmpty private List<TicketDTO> ticketList; } @Data public class TicketDTO { @NotBlank private String cardNo; @NotBlank @Pattern(regexp = "[0-1]") private String faceStatus; @NotBlank @Size(min = 18, max = 18) private String idNumber; @NotBlank private String name; @NotBlank @Pattern(regexp = "[0-1]") private String numberType; @NotBlank @Pattern(regexp = "[0-1]") private String ticketStatus; @NotBlank private String ticketTypeName; } ``` 生产级保障措施: 1. 并发控制: - 使用Redisson分布式锁保证同一展览ID的请求串行处理 - 数据库唯一索引防止数据重复(exhibition_id + card_no组合唯一) - 批量插入使用INSERT IGNORE避免重复 2. 性能优化: - MyBatis-Plus开启批量操作模式(配置文件中添加:`mybatis-plus.configuration.default-executor-type=batch`) - MySQL连接池配置HikariCP: ```yaml spring: datasource: hikari: maximum-pool-size: 20 connection-timeout: 30000 idle-timeout: 600000 max-lifetime: 1800000 ``` 3. 异常处理: - 全局异常处理器捕获DuplicateKeyException - 事务管理保证数据一致性 4. 安全校验: - 使用@Valid进行参数校验 - 身份证号正则校验 - 状态字段枚举值校验 测试建议: ```java // 测试用例 @SpringBootTest class ExhibitionServiceTest { @Autowired private ExhibitionService service; @Test void testConcurrentInsert() throws InterruptedException { int threadCount = 100; ExecutorService executor = Executors.newFixedThreadPool(threadCount); CountDownLatch latch = newCountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { executor.execute(() -> { try { ExhibitionRequestDTO dto = buildTestDTO(); service.processExhibition(dto); } finally { latch.countDown(); } }); } latch.await(); // 验证数据库实际插入数量 } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值