ImageCodeHandler.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.kxs.admin.api.handler;
  2. import cn.hutool.captcha.CaptchaUtil;
  3. import cn.hutool.captcha.LineCaptcha;
  4. import cn.hutool.captcha.generator.RandomGenerator;
  5. import com.kxs.common.core.constant.CacheConstants;
  6. import com.kxs.common.core.constant.SecurityConstants;
  7. import lombok.RequiredArgsConstructor;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.core.io.ByteArrayResource;
  10. import org.springframework.data.redis.core.RedisTemplate;
  11. import org.springframework.data.redis.serializer.StringRedisSerializer;
  12. import org.springframework.http.HttpStatus;
  13. import org.springframework.http.MediaType;
  14. import org.springframework.util.FastByteArrayOutputStream;
  15. import org.springframework.web.servlet.function.HandlerFunction;
  16. import org.springframework.web.servlet.function.ServerRequest;
  17. import org.springframework.web.servlet.function.ServerResponse;
  18. import java.util.Optional;
  19. import java.util.concurrent.TimeUnit;
  20. /**
  21. * 验证码生成逻辑处理类
  22. *
  23. * @author 没秃顶的码农
  24. * @date 2023/11/03
  25. */
  26. @Slf4j
  27. @RequiredArgsConstructor
  28. public class ImageCodeHandler implements HandlerFunction<ServerResponse> {
  29. private static final Integer DEFAULT_IMAGE_WIDTH = 100;
  30. private static final Integer DEFAULT_IMAGE_HEIGHT = 40;
  31. private final RedisTemplate<String, Object> redisTemplate;
  32. @Override
  33. public ServerResponse handle(ServerRequest serverRequest) {
  34. // 保存验证码信息
  35. Optional<String> randomStr = serverRequest.param("randomStr");
  36. //生成验证码
  37. RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
  38. LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);
  39. lineCaptcha.setGenerator(randomGenerator);
  40. redisTemplate.setKeySerializer(new StringRedisSerializer());
  41. randomStr.ifPresent(s -> redisTemplate.opsForValue()
  42. .set(CacheConstants.DEFAULT_CODE_KEY + s, lineCaptcha.getCode(), SecurityConstants.CODE_TIME, TimeUnit.SECONDS));
  43. // 转换流信息写出
  44. FastByteArrayOutputStream os = new FastByteArrayOutputStream();
  45. lineCaptcha.write(os);
  46. return ServerResponse.status(HttpStatus.OK)
  47. .contentType(MediaType.IMAGE_JPEG)
  48. .body(new ByteArrayResource(os.toByteArray()));
  49. }
  50. }