获取唯一的短邀请码

方法一

	/**
     * 获取唯一的邀请码
     *
     * @return the string
     */
    private String generateUserUniqueShareCode() {
        Set<String> arr = getSetArr();

        String code;
        do {
            code = generateCode(arr);
        } while (isCodeUserExists(code));

        return code;
    }

    /**
     * Gets set arr.
     *
     * @return the set arr
     */
    @NotNull
    private static Set<String> getSetArr() {
        return new HashSet<>(Arrays.asList(
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                "a", "b", "c", "d", "e", "f", "g", "h", "j", "k", "m",
                "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y",
                "z", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
                "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
                "Y", "Z"
        ));
    }


    /**
     * 获取随机邀请码
     *
     * @param arr the arr
     * @return the string
     */
    private String generateCode(Set<String> arr) {
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            code.append(new ArrayList<>(arr).get(random.nextInt(arr.size())));
        }
        return code.toString();
    }


    /**
     * 判断邀请码是否存在
     *
     * @param code the code
     * @return the boolean
     */
    private boolean isCodeUserExists(String code) {
        LambdaQueryWrapper<BusinessUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessUser::getShareCode, code);
        return businessUserService.getOne(queryWrapper) != null;
    }

并且需要在parent的pom.xml中添加notnull引用

      <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

方法二

	/**
	 * 获取唯一的邀请码
	 *
	 * @return the string
	 */
	private String generateUserUniqueShareCode() {
	    String code;
	    do {
	        code = generateCode();
	    } while (isCodeUserExists(code));
	
	    return code;
	}
	
	/**
	 * 获取随机邀请码
	 *
	 * @return the string
	 */
	private String generateCode() {
	    StringBuilder code = new StringBuilder("130600"); // 添加前缀
	    Random random = new Random();
	    for (int i = 0; i < 6; i++) {
	        code.append(random.nextInt(10)); // 生成一位随机数字并添加到字符串构建器
	    }
	    return code.toString();
	}
	
	/**
	 * 判断邀请码是否存在
	 *
	 * @param code the code
	 * @return the boolean
	 */
	private boolean isCodeUserExists(String code) {
	    LambdaQueryWrapper<BusinessUser> queryWrapper = new LambdaQueryWrapper<>();
	    queryWrapper.eq(BusinessUser::getShareCode, code);
	    return businessUserService.getOne(queryWrapper) != null;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值