Springboot基于redis的接口防止刷数据的注解
首先是写一个注解类:
1 @Retention(RUNTIME) 2 @Target(METHOD) 3 public @interface AccessLimit { 4 5 int seconds(); 6 int maxCount(); 7 boolean needLogin()default true; 8 }
接着就是在Interceptor拦截器中实现:
1 2 @Component 3 public class FangshuaInterceptor extends HandlerInterceptorAdapter { 4 5 @Autowired 6 private RedisService redisService; 7 8 @Override 9 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 10 11 //判断请求是否属于方法的请求 12 if(handler instanceof HandlerMethod){ 13 14 HandlerMethod hm = (HandlerMethod) handler; 15 16 //获取方法中的注解,看是否有该注解 17 AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class); 18 if(accessLimit == null){ 19 return true; 20 } 21 int seconds = accessLimit.seconds(); 22 int maxCount = accessLimit.maxCount(); 23 boolean login = accessLimit.needLogin(); 24 String key = request.getRequestURI(); 25 //如果需要登录 26 if(login){ 27 //获取登录的session进行判断 28 //..... 29 key+=""+"1"; //这里假设用户是1,项目中是动态获取的userId 30 } 31 32 //从redis中获取用户访问的次数 33 AccessKey ak = AccessKey.withExpire(seconds); 34 Integer count = redisService.get(ak,key,Integer.class); 35 if(count == null){ 36 //第一次访问 37 redisService.set(ak,key,1); 38 }else if(count < maxCount){ 39 //加1 40 redisService.incr(ak,key); 41 }else{ 42 //超出访问次数 43 render(response,CodeMsg.ACCESS_LIMIT_REACHED); //这里的CodeMsg是一个返回参数 44 return false; 45 } 46 } 47 48 return true; 49 50 } 51 private void render(HttpServletResponse response, CodeMsg cm)throws Exception { 52 response.setContentType("application/json;charset=UTF-8"); 53 OutputStream out = response.getOutputStream(); 54 String str = JSON.toJSONString(Result.error(cm)); 55 out.write(str.getBytes("UTF-8")); 56 out.flush(); 57 out.close(); 58 } 59 }
再把Interceptor注册到springboot中
1 @Configuration 2 public class WebConfig extends WebMvcConfigurerAdapter { 3 4 @Autowired 5 private FangshuaInterceptor interceptor; 6 7 8 @Override 9 public void addInterceptors(InterceptorRegistry registry) { 10 registry.addInterceptor(interceptor); 11 } 12 }
接着在Controller中加入注解
1 @Controller 2 public class FangshuaController { 3 4 @AccessLimit(seconds=5, maxCount=5, needLogin=true) 5 @RequestMapping("/fangshua") 6 @ResponseBody 7 public Result<String> fangshua(){ 8 9 10 return Result.success("请求成功"); 11 12 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具