本文将介绍在spring项目中自定义注解,借助redis实现接口的限流

自定义注解类


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* 基于注解的请求限制
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessLimit {
/**
* 请求限制数
* @return
*/
int limit(); /**
* 时间范围
* @return
*/
int timeScope(); }

使用注解

我们在需要进行接口防刷的类或者方法上加上该注解即可,


/**
* 得到秒杀地址
* 由于秒杀地址较为重要和敏感,为了防止恶意用户刷接口,
* 我们将秒杀接口作为动态的
* @param user
* @param goodsId
* @param tryCode
* @return
*/
@GetMapping("/path")
@ResponseBody
@AccessLimit(limit = 5, timeScope = 5) // 限制5秒内只能请求5次
public Result<String> getMiaoshaPath(HttpServletRequest request, User user, long goodsId, String tryCode) {
// 验证码校验
Boolean verifyPass = kaptchaService.imgVerifyCode(user, goodsId, tryCode);
if (!verifyPass) {
log.info("【执行秒杀】-- 验证码错误");
throw new FlashSaleException(KAPTCHA_VERIFY_FAIL);
}
String path = miaoshaService.createPath(user, goodsId);
return Result.success(path);
};

使用拦截器,在拦截方法时拿到注解上的属性

 @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 从redis中取到值
Cookie cookie = CookieUtil.get(request, Constants.Cookie.TOKEN);
if (cookie == null) {
throw new FlashSaleException(AuthFailEnum.COOKIE_HAVE_NO_TOKEN);
}
StringRedisTemplate redisTemplate = ApplicationContextHolder.get().getBean("stringRedisTemplate", StringRedisTemplate.class);
String userStr = redisTemplate.opsForValue().get(cookie.getValue());
if (StringUtils.isEmpty(userStr)) {
throw new FlashSaleException(AuthFailEnum.REDIS_HAVE_NOT_TOKEN);
}
User user = JSON.parseObject(userStr, User.class);
UserContextHolder.set(user);
if (handler instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod) handler;
// 拿到注解的内容
AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
if (accessLimit == null) {
// 不需要限流验证
return true;
} else {
// 需要限流验证
int limit = accessLimit.limit();
int timeScope = accessLimit.timeScope();
// 次数校验(借助redis实现基于用户的限流验证)
String requestURI = request.getRequestURI();
final String redisKey = Constants.Cache.PATH_COUNT_PREFIX + user.getId() + ":" + requestURI;
String currentCount = redisTemplate.opsForValue().get(redisKey);
if (!StringUtils.isEmpty(currentCount)) {
int count = Integer.valueOf(currentCount);
if (count < limit) {
redisTemplate.opsForValue().increment(redisKey, 1);
} else {
// 访问过于频繁
throw new FlashSaleException(PATH_LIMIT_REACHED);
}
} else {
redisTemplate.opsForValue().set(redisKey, "1", timeScope, TimeUnit.SECONDS);
}
}
}
UserContextHolder.set(user);
renewExpiretime(response, cookie, userStr);
return true;
}

总结

 在实现了上述代码后,当我们访问到带有AccessLimit注解的方法或类时,只要拦截器拦截了该请求,就能通过getMethodAnnotation()拿到注解上的limit和timeScope属性,然后借助redis实现限流;比如某些接口我们可能想要2秒只能访问1次,那么就把limit=1 timeScope=2,某些接口我们想要限制1分钟访问10次,就把limit=10, timeScope=60

spring中实现基于注解实现动态的接口限流防刷的更多相关文章

  1. SpringBoot使用自定义注解+AOP+Redis实现接口限流

    为什么要限流 系统在设计的时候,我们会有一个系统的预估容量,长时间超过系统能承受的TPS/QPS阈值,系统有可能会被压垮,最终导致整个服务不可用.为了避免这种情况,我们就需要对接口请求进行限流. 所以 ...

  2. 使用 Spring 2.5 基于注解驱动的 Spring MVC

    http://www.ibm.com/developerworks/cn/java/j-lo-spring25-mvc/ 概述 继 Spring 2.0 对 Spring MVC 进行重大升级后,Sp ...

  3. 使用 Spring 2.5 基于注解驱动的 Spring MVC--转

    概述 继 Spring 2.0 对 Spring MVC 进行重大升级后,Spring 2.5 又为 Spring MVC 引入了注解驱动功能.现在你无须让 Controller 继承任何接口,无需在 ...

  4. JavaEE开发之Spring中的条件注解组合注解与元注解

    上篇博客我们详细的聊了<JavaEE开发之Spring中的多线程编程以及任务定时器详解>,本篇博客我们就来聊聊条件注解@Conditional以及组合条件.条件注解说简单点就是根据特定的条 ...

  5. JavaEE开发之Spring中的条件注解、组合注解与元注解

    上篇博客我们详细的聊了<JavaEE开发之Spring中的多线程编程以及任务定时器详解>,本篇博客我们就来聊聊条件注解@Conditional以及组合条件.条件注解说简单点就是根据特定的条 ...

  6. 第5章—构建Spring Web应用程序—关于spring中的validate注解后台校验的解析

    关于spring中的validate注解后台校验的解析 在后台开发过程中,对参数的校验成为开发环境不可缺少的一个环节.比如参数不能为null,email那么必须符合email的格式,如果手动进行if判 ...

  7. Spring 中aop切面注解实现

    spring中aop的注解实现方式简单实例   上篇中我们讲到spring的xml实现,这里我们讲讲使用注解如何实现aop呢.前面已经讲过aop的简单理解了,这里就不在赘述了. 注解方式实现aop我们 ...

  8. spring中使用@Async注解进行异步处理

    引言: 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的:但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在spring 3. ...

  9. Spring中的常用注解

    Spring中的常用注解 1.@Controller 标识一个该类是Spring MVC controller处理器,用来创建处理http请求的对象.

随机推荐

  1. 邓 【PHP大全】

    获取对应的时间戳(只保存月底的时间戳) function getTimeDate($timeType, $time, $count) { switch ($timeType) { case 'MONT ...

  2. MySql学习-3.命令脚本

    一.数据库操作: 1. 登录数据库:mysql -uroot -p (这个password是自己设定的,我这里的没密码) 注意:(数据路径是:D:\MySql\install1\data 操作路径:D ...

  3. CommonJs模块化(nodejs模块规范)

    1.概述: Node应用由模块组成,采用CommonJS模块规范. 根据这个规范,每个文件就是一个模块,有自己的作用域.在一个文件里面定义的变量.函数.类,都是私有的,对其他文件不可见. 如果想在多个 ...

  4. js的reduce累加器

    reduce为数组中每一个元素执行回调函数,不包括被删除或未被赋值的 https://www.jianshu.com/p/e375ba1cfc47

  5. 两种从 TensorFlow 的 checkpoint生成 frozenpb 的方法

    1. 从 ckpt-.data,ckpt-.index 和 .meta 生成 frozenpb import os import tensorflow as tf from tensorflow.py ...

  6. 9个常用的正则表达式-sunziren

    正数字:/^[1-9]{1}[0-9]*$|^0{1}\.{1}[0-9]+$|^[1-9]{1}[0-9]*\.{1}[0-9]+$/ 用户名:/^[a-z0-9_-]{3,16}$/ 密码:/^[ ...

  7. day 15 内置函数

    内置函数 不用def定义能直接用的函数,带括号的 locals() # 返回本地作用域中的所有名字 globals() # 返回全局作用域中的所有名字 global 变量 nonlocal 变量 迭代 ...

  8. 洛谷P4525 【模板】自适应辛普森法1与2

    洛谷P4525 [模板]自适应辛普森法1 与P4526[模板]自适应辛普森法2 P4525洛谷传送门 P4525题目描述 计算积分 结果保留至小数点后6位. 数据保证计算过程中分母不为0且积分能够收敛 ...

  9. 使用pip安装Python库超时解决办法

    如果在国内安装Python库,强烈推荐使用豆瓣的源http://pypi.douban.com/simple/ 可以这样使用 pip install -i http://pypi.douban.com ...

  10. nginx配置location与rewrite规则教程

    location 教程 location 教程 示例: location = / { # 精确匹配 / ,主机名后面不能带任何字符串 [ configuration A ] }location / { ...