方法一
/**
* 获取唯一的邀请码
*
* @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;
}