SpringBoot使用@Async异步调用方法

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

2、解决方案 

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

3、启动类添加注解

@EnableAsync // 开启异步任务

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

@Async
package com.ahies.stm.app.synthesizes.sys.service.impl;

import com.ahies.stm.app.synthesizes.sys.entity.Message;
import com.ahies.stm.app.synthesizes.sys.mapper.MessageMapper;
import com.ahies.stm.app.synthesizes.sys.service.MessageService;
import com.ahies.stm.app.base.BaseServiceImpl;
import com.ahies.stm.app.util.AliSendMessageUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;


@Service
@Transactional
public class MessageServiceImpl extends BaseServiceImpl<MessageMapper, Message> implements MessageService {

    @Value("${accessKeyId}")
    private String accessKeyId;

    @Value("${accessKeySecret}")
    private String accessKeySecret;

    @Value("${templatecode.forgetpassword}")
    private String templatecode;

    @Value("${sign}")
    private String sign;
    /*
    * @Description: 异步调用有返回值的阿里发送短信的方法
    * @param  phone, code 
    * @return java.util.concurrent.Future<java.lang.Boolean>
    * @menu /
    * @status done
    */
    @Async
    @Override
    public Future<Boolean> sendMessage(String phone, String code) {
        Map<String, String> param = new HashMap<>();
        param.put("code", code);
        boolean flag = AliSendMessageUtils.sendMessage(accessKeyId, accessKeySecret, phone, templatecode, sign, param);
        return new AsyncResult<>(flag);
    }
}

4、后台发送短信的接口

 

package com.ahies.stm.app.interactive.index;

import com.ahies.stm.app.base.BaseController;
import com.ahies.stm.app.constant.SysConstant;
import com.ahies.stm.app.synthesizes.staff.entity.Member;
import com.ahies.stm.app.synthesizes.staff.service.MemberService;
import com.ahies.stm.app.synthesizes.sys.entity.Message;
import com.ahies.stm.app.synthesizes.sys.service.MessageService;
import com.ahies.stm.app.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/interactive/index/login")
@CrossOrigin
public class MemberLoginController extends BaseController {



    @Autowired
    MessageService messageService;
    @Autowired
    RedissonClient redissonClient;
    @Value("${accessKeyId}")
    private String accessKeyId;

    @Value("${accessKeySecret}")
    private String accessKeySecret;

    @Value("${templatecode.forgetpassword}")
    private String templatecode;

    @Value("${sign}")
    private String sign;



   
    @RequestMapping("/authenticode")
    public ResponseResult<String> authenticode(@RequestParam(name = "phone") String phone,
                                               @RequestParam(name = "ckeckPhone", required = false) String ckeckPhone) {
        if (StringUtils.isNotBlank(ckeckPhone)) {
            QueryWrapper<Member> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(Member::getPhoneNum, phone);
            Member member = memberService.getOne(wrapper);
            if (null == member) {
                return ResponseResult.dataFailed(null, SysConstant.PHONE_NOT_EXITS);
            }
        }
        RBucket<String> rBucket = redissonClient.getBucket(SysConstant.AUTHENTICODE_KEY_PRE + phone);
        String authenticode = "";
        boolean flag = false;
        if (StringUtils.isBlank(rBucket.get())) {
            authenticode = String.valueOf((int) (Math.random() * 900000 + 100000));
            String content = "您本次服务的验证码为" + authenticode + ",请在10分钟内使用。请勿向他人透露您的验证码。";
            Map<String, String> param = new HashMap<>();
            param.put("code", authenticode);
            Future<Boolean> future = messageService.sendMessage(phone, authenticode);
            try {
                flag = future.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
//            flag = AliSendMessageUtils.sendMessage(accessKeyId, accessKeySecret, phone, templatecode, sign, param);
            Message message = Message.builder().phone(phone).code(authenticode).content(content)
                    .build();
            messageService.save(message);
            rBucket.set(authenticode, 10, TimeUnit.MINUTES);
        } else {
            authenticode = rBucket.get();
            rBucket.set(authenticode, 10, TimeUnit.MINUTES);
            flag = true;
        }

        if (flag) {
            return ResponseResult.dataSuccess(authenticode, SysConstant.SEND_SUCCESS);
        }
        return ResponseResult.dataFailed(authenticode, SysConstant.SEND_FAIL);

    }

 
   


}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非ban必选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值