java-避免同时执行两次@Async 任务

最近我们项目有个统计实时库存的接口,数据量过大导致每次调用都超时,导致页面一片空白。

为了不影响使用,我将库存信息存到一张新的表里面,通过定时任务定时计算更新库存。同时也可以让用户异步的去手动更新实时库存。这样也不影响用户在前端页面查看。

那么如果是异步更新的话,如果同一个用户同时点击多次,该怎么去避免呢?

首先我的接口代码:

 @GetMapping("refresh-inventory")
    @ApiOperation("一健刷新实时库存")
    public ResultDto<ProjectCurrentInventoryDto> refreshInventory() {
        ResultDto resultDto = new ResultDto();
        try{
            String userId = SecurityUserHolder.getCurrentUserId();
            List<Integer> projectIds = manageService.queryCompanyIdByUser(userId);
            //异步方法
            tahGoodsService.setSemaphore(userId, projectIds);
            resultDto.setData("刷新中.....");
        }catch (Exception e){
            resultDto.setError("操作失败");
            e.printStackTrace();
        }
        return resultDto;
    }

setSemaphore是一个异步方法,具体代码如下:

// Init on startup
    // Key should be a unique identifier to a company, I assume the `String company` as key, you should adjust as your real requirement
    static final Map<String, Semaphore> COMPANY_ENTRANT = new ConcurrentHashMap<>();

    /**
     * 防止重复点击刷新
     * @param userId
     * @param projectIds
     */
    @Async
    @Override
    public void setSemaphore(String userId, List<Integer> projectIds){
        Semaphore entrant = COMPANY_ENTRANT.putIfAbsent(userId, new Semaphore(1));
        if(entrant==null){
            COMPANY_ENTRANT.put(userId, new Semaphore(1));
            entrant = COMPANY_ENTRANT.get(userId);
        }
        try{
            entrant.acquire();
            //计算实时库存
            updateCurrentInventory(projectIds);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            entrant.release();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值