SpringBoot使用@Async异步调用方法

朱雀 2023-06-24 12:29 78阅读 0赞

1、业务场景,在使用阿里大鱼发送短信时,不知因何原因,后端接口发送短信较耗时,前端请求后端接口很快出现请求错误,这跟前端设置的响应时间相关,可以让前端增加时间,但这并不是一个好的解决方法。

2、解决方案

使用异步调用阿里发送短信的方案。

3、启动类添加注解

  1. @EnableAsync // 开启异步任务

4、异步调用,方法加注解

  1. @Async
  2. package com.ahies.stm.app.synthesizes.sys.service.impl;
  3. import com.ahies.stm.app.synthesizes.sys.entity.Message;
  4. import com.ahies.stm.app.synthesizes.sys.mapper.MessageMapper;
  5. import com.ahies.stm.app.synthesizes.sys.service.MessageService;
  6. import com.ahies.stm.app.base.BaseServiceImpl;
  7. import com.ahies.stm.app.util.AliSendMessageUtils;
  8. import org.springframework.beans.factory.annotation.Value;
  9. import org.springframework.scheduling.annotation.Async;
  10. import org.springframework.scheduling.annotation.AsyncResult;
  11. import org.springframework.stereotype.Service;
  12. import org.springframework.transaction.annotation.Transactional;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. import java.util.concurrent.Future;
  16. @Service
  17. @Transactional
  18. public class MessageServiceImpl extends BaseServiceImpl<MessageMapper, Message> implements MessageService {
  19. @Value("${accessKeyId}")
  20. private String accessKeyId;
  21. @Value("${accessKeySecret}")
  22. private String accessKeySecret;
  23. @Value("${templatecode.forgetpassword}")
  24. private String templatecode;
  25. @Value("${sign}")
  26. private String sign;
  27. /*
  28. * @Description: 异步调用有返回值的阿里发送短信的方法
  29. * @param phone, code
  30. * @return java.util.concurrent.Future<java.lang.Boolean>
  31. * @menu /
  32. * @status done
  33. */
  34. @Async
  35. @Override
  36. public Future<Boolean> sendMessage(String phone, String code) {
  37. Map<String, String> param = new HashMap<>();
  38. param.put("code", code);
  39. boolean flag = AliSendMessageUtils.sendMessage(accessKeyId, accessKeySecret, phone, templatecode, sign, param);
  40. return new AsyncResult<>(flag);
  41. }
  42. }

4、后台发送短信的接口

  1. package com.ahies.stm.app.interactive.index;
  2. import com.ahies.stm.app.base.BaseController;
  3. import com.ahies.stm.app.constant.SysConstant;
  4. import com.ahies.stm.app.synthesizes.staff.entity.Member;
  5. import com.ahies.stm.app.synthesizes.staff.service.MemberService;
  6. import com.ahies.stm.app.synthesizes.sys.entity.Message;
  7. import com.ahies.stm.app.synthesizes.sys.service.MessageService;
  8. import com.ahies.stm.app.util.*;
  9. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  10. import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
  11. import org.apache.commons.lang3.StringUtils;
  12. import org.redisson.api.RBucket;
  13. import org.redisson.api.RedissonClient;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.beans.factory.annotation.Value;
  16. import org.springframework.web.bind.annotation.CrossOrigin;
  17. import org.springframework.web.bind.annotation.RequestMapping;
  18. import org.springframework.web.bind.annotation.RequestParam;
  19. import org.springframework.web.bind.annotation.RestController;
  20. import java.util.HashMap;
  21. import java.util.Map;
  22. import java.util.concurrent.ExecutionException;
  23. import java.util.concurrent.Future;
  24. import java.util.concurrent.TimeUnit;
  25. @RestController
  26. @RequestMapping("/interactive/index/login")
  27. @CrossOrigin
  28. public class MemberLoginController extends BaseController {
  29. @Autowired
  30. MessageService messageService;
  31. @Autowired
  32. RedissonClient redissonClient;
  33. @Value("${accessKeyId}")
  34. private String accessKeyId;
  35. @Value("${accessKeySecret}")
  36. private String accessKeySecret;
  37. @Value("${templatecode.forgetpassword}")
  38. private String templatecode;
  39. @Value("${sign}")
  40. private String sign;
  41. @RequestMapping("/authenticode")
  42. public ResponseResult<String> authenticode(@RequestParam(name = "phone") String phone,
  43. @RequestParam(name = "ckeckPhone", required = false) String ckeckPhone) {
  44. if (StringUtils.isNotBlank(ckeckPhone)) {
  45. QueryWrapper<Member> wrapper = new QueryWrapper<>();
  46. wrapper.lambda().eq(Member::getPhoneNum, phone);
  47. Member member = memberService.getOne(wrapper);
  48. if (null == member) {
  49. return ResponseResult.dataFailed(null, SysConstant.PHONE_NOT_EXITS);
  50. }
  51. }
  52. RBucket<String> rBucket = redissonClient.getBucket(SysConstant.AUTHENTICODE_KEY_PRE + phone);
  53. String authenticode = "";
  54. boolean flag = false;
  55. if (StringUtils.isBlank(rBucket.get())) {
  56. authenticode = String.valueOf((int) (Math.random() * 900000 + 100000));
  57. String content = "您本次服务的验证码为" + authenticode + ",请在10分钟内使用。请勿向他人透露您的验证码。";
  58. Map<String, String> param = new HashMap<>();
  59. param.put("code", authenticode);
  60. Future<Boolean> future = messageService.sendMessage(phone, authenticode);
  61. try {
  62. flag = future.get();
  63. } catch (InterruptedException e) {
  64. e.printStackTrace();
  65. } catch (ExecutionException e) {
  66. e.printStackTrace();
  67. }
  68. // flag = AliSendMessageUtils.sendMessage(accessKeyId, accessKeySecret, phone, templatecode, sign, param);
  69. Message message = Message.builder().phone(phone).code(authenticode).content(content)
  70. .build();
  71. messageService.save(message);
  72. rBucket.set(authenticode, 10, TimeUnit.MINUTES);
  73. } else {
  74. authenticode = rBucket.get();
  75. rBucket.set(authenticode, 10, TimeUnit.MINUTES);
  76. flag = true;
  77. }
  78. if (flag) {
  79. return ResponseResult.dataSuccess(authenticode, SysConstant.SEND_SUCCESS);
  80. }
  81. return ResponseResult.dataFailed(authenticode, SysConstant.SEND_FAIL);
  82. }
  83. }

发表评论

表情:
评论列表 (有 0 条评论,78人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot使用@Async异步调用方法

    1、业务场景,在使用阿里大鱼发送短信时,不知因何原因,后端接口发送短信较耗时,前端请求后端接口很快出现请求错误,这跟前端设置的响应时间相关,可以让前端增加时间,但这并不是一个好