ImageCodeHandler.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package com.kxs.gateway.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.reactive.function.BodyInserters;
  16. import org.springframework.web.reactive.function.server.HandlerFunction;
  17. import org.springframework.web.reactive.function.server.ServerRequest;
  18. import org.springframework.web.reactive.function.server.ServerResponse;
  19. import reactor.core.publisher.Mono;
  20. import java.util.Optional;
  21. import java.util.concurrent.TimeUnit;
  22. /**
  23. * 验证码生成逻辑处理类
  24. *
  25. * @author 没秃顶的码农
  26. * @date 2023/11/03
  27. */
  28. @Slf4j
  29. @RequiredArgsConstructor
  30. public class ImageCodeHandler implements HandlerFunction<ServerResponse> {
  31. private static final Integer DEFAULT_IMAGE_WIDTH = 100;
  32. private static final Integer DEFAULT_IMAGE_HEIGHT = 40;
  33. private final RedisTemplate<String, Object> redisTemplate;
  34. @Override
  35. public Mono<ServerResponse> handle(ServerRequest serverRequest) {
  36. // 保存验证码信息
  37. Optional<String> randomStr = serverRequest.queryParam("randomStr");
  38. // 生成验证码
  39. RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
  40. LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);
  41. lineCaptcha.setGenerator(randomGenerator);
  42. redisTemplate.setKeySerializer(new StringRedisSerializer());
  43. randomStr.ifPresent(s -> redisTemplate.opsForValue()
  44. .set(CacheConstants.DEFAULT_CODE_KEY + s, lineCaptcha.getCode(), SecurityConstants.CODE_TIME,
  45. TimeUnit.SECONDS));
  46. // 转换流信息写出
  47. FastByteArrayOutputStream os = new FastByteArrayOutputStream();
  48. lineCaptcha.write(os);
  49. return ServerResponse.status(HttpStatus.OK)
  50. .contentType(MediaType.IMAGE_JPEG)
  51. .body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
  52. }
  53. }