1. 通过注解的形式实现通用接口访问次数限制

(1)pom.xml文件中引入expiringmap

 <dependency>
      <groupId>net.jodah</groupId>
      <artifactId>expiringmap</artifactId>
      <version>0.5.10</version>
 </dependency>

(2)添加注解

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LimitRequest {
    //请求时间
    long time() default 60 * 1000;
    //请求次数
    int count() default Integer.MAX_VALUE;
}

(3)添加注解对应解析类

@Aspect
@Component
public class LimitRequestAspect {
    private static ConcurrentHashMap<String, ExpiringMap<String, Integer>> hashMap = new ConcurrentHashMap<>();

    @Pointcut("@annotation(limitRequest)")
    public void excudeService(LimitRequest limitRequest) {
    }

    @Around("excudeService(limitRequest)")
    public Object doAround(ProceedingJoinPoint pjp, LimitRequest limitRequest) throws Throwable {

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        ExpiringMap<String, Integer> map = hashMap.getOrDefault(request.getRequestURI(), ExpiringMap.builder().variableExpiration().build());
        Integer count = map.getOrDefault(request.getRemoteAddr(), 0);

        if (count >= limitRequest.count()) {
            throw new BusinessException(500, "访问次数超过限制");
        } else if (count == 0) {
            map.put(request.getRemoteAddr(), count + 1, ExpirationPolicy.CREATED, limitRequest.time(), TimeUnit.MILLISECONDS);
        } else {
            map.put(request.getRemoteAddr(), count + 1);
        }
        hashMap.put(request.getRequestURI(), map);
        Object result = pjp.proceed();

        return result;
    }
}

然后就可以在接口上添加对应的注解@LimitRequest(time=60*1000, count = 3) 来限制时间范围内请求次数了。

2. 针对特殊接口

思路:通过redis 失效时间来控制时间范围内请求次数

String commentKey = String.format("comment:%d:%d", comment.getBusinessId(), comment.getUserId());
Long count = redisTemplate.opsForValue().increment(commentKey);
if (count > 10) {
     throw new BusinessException("发表评论过于频繁,休息下再操作吧~");
   }
redisTemplate.expire(commentKey, 30, TimeUnit.SECONDS);

 

原文地址:http://www.cnblogs.com/wlong-blog/p/16925999.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性