Java 使用 Redis 生成图片(未使用Session ),主要目的是防止机器刷单

1、设置 Maven

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>

2、设置一个随机字符串(用来存在 Redis 中作为图片的 key)

1
2
3
4
5
6
@GetMapping("/getToken")
public String getToken() {
//生成唯一字符串作为token
String token = UUID.randomUUID().toString();
return token;
}

3、生成验证码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@PostMapping("/getcode")
public void getCode(HttpServletResponse response,String token) throws Exception {

// 返回的数组第一个参数是生成的验证码,第二个参数是生成的图片
Object[] objs = VerifyUtil.newBuilder()
.setWidth(100) //设置图片的宽度
.setHeight(35) //设置图片的高度
.setSize(4) //设置字符的个数
.setLines(3) //设置干扰线的条数
.setFontSize(25) //设置字体的大小
.setTilt(false) //设置是否需要倾斜
.setBackgroundColor(Color.LIGHT_GRAY) //设置验证码的背景颜色
.build() //构建VerifyUtil项目
.createImage(); //生成图片
// 打印验证码
System.out.println(objs[0]);

// 设置redis值的序列化方式
redisTemplate.setValueSerializer(new StringRedisSerializer());
// 在redis中保存一个验证码最多尝试次数
redisTemplate.opsForValue().set(("VERIFY_CODE_" + 1), "3", 5 * 60, TimeUnit.SECONDS);


String buyCode = String.valueOf(objs[0]);
String buyKey = "buy_" + token;

RedisUtils.set(buyKey, buyCode, 60 * 1 + 5);//redis中的code比实际要多5秒


// 将图片输出给浏览器
BufferedImage image = (BufferedImage) objs[1];
response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(image, "png", os);


}

4、验证验证码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@PostMapping("/checkcode")
public JsonResult checkCode(String code, HttpServletRequest request,String token) {
JsonResult result = new JsonResult();
String buyKey = "buy_" + token;
String codeCheck = RedisUtils.get(buyKey);
Long times = RedisUtils.ttl(buyKey);
if (times == -2) {
result.setSuccess(true);
result.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
result.setMsg("验证码过期");
return result;
}
if (codeCheck.equals(code)) {
result.setSuccess(true);
result.setCode(HttpStatus.SC_OK);
result.setMsg("验证码正确");
return result;
}
result.setSuccess(true);
result.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
result.setMsg("请输入正确的验证码");
return result;
}

如果需要 Redis工具类可以在下面留言备注邮箱


Java 使用 Redis 生成图片(未使用Session ),主要目的是防止机器刷单
https://tdsgpo.top/2022/04/21/Java 使用 Redis生成图片(未使用Session )/
作者
DDS
发布于
2022年4月21日
许可协议