商城系统开发从0到1(Redis实现拦截重复请求)

 private boolean limitRequest(String id) {
        boolean result = false;
        String key = String.format("id:%s", id);
        BoundZSetOperations<String, String> zSetOperations = stringRedisTemplate
            .boundZSetOps(key);
        Instant now = Instant.now();
        long epochSecond = now.getEpochSecond();
        long milliOfSecond = now.getLong(ChronoField.MILLI_OF_SECOND);
        zSetOperations.add(String.format("%d.%d", epochSecond, milliOfSecond), epochSecond);
        zSetOperations.expire(3, TimeUnit.MINUTES);
        zSetOperations.removeRangeByScore(0, now.plusSeconds(-5).getEpochSecond());
        Long orderTimes = Optional.ofNullable(zSetOperations.zCard()).orElse(0L);
        if (orderTimes > 1) {
            result = true;
        }
        return result;
    }

 

在Controller里面调用这个方法,,这里的id要换成自己的业务id,已确保是同个用户发起的请求。使用了Redis的BoundZSetOp

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值