基本上每一个系统要有生成验证码的功能。
生成验证码的规则有很多种,在并发量大的系统中,一个好的验证码生成逻辑可以大大提高qps,那如何生成6位数的验证码呢
方式1:
使用可变长度字符串StirngBuilder,并逐个append每一个随机数
StringBuilder builder = new StringBuilder();
for (int j = 0; j < 6; j++) {
String num = String.valueOf(random.nextInt(10));
builder.append(num);
}
String code = builder.toString();
方式2
通过截取Math.random()
生成6位验证码
String code = (Math.random() + "").substring(2, 8);
方式3
通过直接进行数学计算生成6位验证码
int num = (int) ((Math.random() * 9 + 1) * (Math.pow(10, 5)));
String code = String.valueOf(num);
说明:
-
Math.random()的范围为 (0,1)
-
Math.random() * 9 + 1 的范围为(1,10)
-
Math.pow(10, 5) 的值恒为六位数的100000
为什么(Math.random() * 9 后又要加1 ? 因为Math.random() * 9 的范围为(0,9),当出现0~1之间的数时,乘以100000会出现小于6位的数字,导致最终生成的验证码位数不统一,因此+1,将范围变为(1,10)
方案4
int code =(int)(Math.random() * 900000 + 100000);
String codeA = String.valueOf(code);
说明:
- Math.random()的范围为 (0,1)
- Math.random() * 900000 的范围为(0,900000),该范围内0~100000会出现小于6位的数字,因此要加100000
加10000以后范围是 (100000,1000000)必为6位数
public static void main(String[] args) {
int nums = 100000;
//-------------------------第一种-------------------------
long start = System.currentTimeMillis();
Random random = new Random();
for (int i = 0; i < nums; i++) {
StringBuilder builder = new StringBuilder();
for (int j = 0; j < 6; j++) {
String num = String.valueOf(random.nextInt(10));
builder.append(num);
}
}
long end = System.currentTimeMillis();
System.out.println("时间为" + (end - start));
//--------------------------第二种------------------------
long start1 = System.currentTimeMillis();
for (int i = 0; i < nums; i++) {
String code = (Math.random() + "").substring(2, 8);
}
long end1 = System.currentTimeMillis();
System.out.println("时间为" + (end1 - start1));
//--------------------------第三种------------------------
long start2 = System.currentTimeMillis();
for (int i = 0; i < nums; i++) {
int num = (int) ((Math.random() * 9 + 1) * (Math.pow(10, 5)));
String code = String.valueOf(num);
}
long end2 = System.currentTimeMillis();
System.out.println("时间为" + (end2 - start2));
//--------------------------第四种------------------------
long start3 = System.currentTimeMillis();
for (int i = 0; i < nums; i++) {
int num = (int) (Math.random() * 900000 + 100000);
String code = String.valueOf(num);
}
long end3 = System.currentTimeMillis();
System.out.println("时间为" + (end3 - start3));
}
建议开发中使用第3、4种,它们是直接在内部进行计算得出来的验证码再转换成String类型,而不像前两种存在大量的对String的操作,操作引用类型在堆上的操作,操作数据类型是在栈上的操作,优劣显而易见