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