【spring boot】异步请求

来源:互联网 发布:mpiigaze数据集 编辑:程序博客网 时间:2024/06/05 15:58

PS:这里只记录 异步请求的坑,用法 网上很多,在此就不做记录了。

需求:

在王者荣耀里 有些福利 点击领取却没有实时接收到。例如:点击开启 铠秘宝 提示“奖励通过邮箱发放,由于发货量大,可能会有一定延迟,预计24小时到账”

如何做到:快速响应前端用户的请求,而(耗时比较大)的业务逻辑处理放到后台处理。用法自行百度。

踩过的坑:【调用方和被调用方都在同一个service中 异步无效】


错误范例:这样 method方法不会快速响应用户的领取请求,还要算上doMethodOne的耗时。

@Service
public class TestServiceImpl {

public String method() {
doMethodOne();
return "奖励通过邮箱发放,由于发货量大,可能会有一定延迟,预计24小时到账";
}

@Async
private void doMethodOne(){
//todo
}
}

正确的范例:

@Service
public class TestServiceImpl {
@Autowired
    private AsyncService asyncService;

public String method() {
asyncService.doMethodOne();
return "奖励通过邮箱发放,由于发货量大,可能会有一定延迟,预计24小时到账";
}

}

@Service
public class AsyncServiceImpl {

@Async
private void doMethodOne(){
//todo 耗时的业务逻辑处理:处理完 发放奖励到用户邮箱
}
}