说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考

技术要点:springboot的基本知识,redis基本操作,

首先是写一个注解类:

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
 
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
 
@Retention(RUNTIME)
@Target(METHOD)
public @interface AccessLimit {
 
    int seconds();
    int maxCount();
    boolean needLogin()default true;
}

接着就是在Interceptor拦截器中实现:

import com.alibaba.fastjson.JSON;
import com.example.demo.action.AccessLimit;
import com.example.demo.redis.RedisService;
import com.example.demo.result.CodeMsg;
import com.example.demo.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
 
@Component
public class FangshuaInterceptor extends HandlerInterceptorAdapter {
 
    @Autowired
    private RedisService redisService;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 
        //判断请求是否属于方法的请求
        if(handler instanceof HandlerMethod){
 
            HandlerMethod hm = (HandlerMethod) handler;
 
            //获取方法中的注解,看是否有该注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if(accessLimit == null){
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean login = accessLimit.needLogin();
            String key = request.getRequestURI();
            //如果需要登录
            if(login){
                //获取登录的session进行判断
                //.....
                key+=""+"1";  //这里假设用户是1,项目中是动态获取的userId
            }
 
            //从redis中获取用户访问的次数
            AccessKey ak = AccessKey.withExpire(seconds);
            Integer count = redisService.get(ak,key,Integer.class);
            if(count == null){
                //第一次访问
                redisService.set(ak,key,1);
            }else if(count < maxCount){
                //加1
                redisService.incr(ak,key);
            }else{
                //超出访问次数
                render(response,CodeMsg.ACCESS_LIMIT_REACHED); //这里的CodeMsg是一个返回参数
                return false;
            }
        }
 
        return true;
 
    }
    private void render(HttpServletResponse response, CodeMsg cm)throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str  = JSON.toJSONString(Result.error(cm));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }
}

再把Interceptor注册到springboot中

import com.example.demo.ExceptionHander.FangshuaInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
 
    @Autowired
    private FangshuaInterceptor interceptor;
 
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor);
    }
}

接着在Controller中加入注解

import com.example.demo.result.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
public class FangshuaController {
 
    @AccessLimit(seconds=5, maxCount=5, needLogin=true)
    @RequestMapping("/fangshua")
    @ResponseBody
    public Result fangshua(){
 
 
        return Result.success("请求成功");
 
    }

IT技术分享社区

个人博客网站:https://programmerblog.xyz

文章推荐程序员效率:画流程图常用的工具程序员效率:整理常用的在线笔记软件远程办公:常用的远程协助软件,你都知道吗?51单片机程序下载、ISP及串口基础知识硬件:断路器、接触器、继电器基础知识

后端技术:一个注解解决 SpringBoot 接口防刷相关推荐

  1. 一个注解搞定接口防刷!还有谁不会?

    点击关注公众号,Java干货及时送达 说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考 一,技术要点:springboot的基本知识,redis基本操作, 首先是写一个注解类: ...

  2. springboot接口防刷实现

    本文主要介绍一种通过实现自定义注解,实现一种比较通用的接口防刷方式 前言 1.基本准备 jdk 8 redis springboot 2.7.6 2.基本思路 主要就是借助 redis 来实现接口的防 ...

  3. 一个注解搞定 SpringBoot 接口防刷,还有谁不会?

    点击上方蓝色"方志朋",选择"设为星标" 回复"666"获取独家整理的学习资料! 作者:CS打赢你 blog.csdn.net/weixin ...

  4. spring boot + redis 实现网站限流和接口防刷功能

    源码url: https://github.com/zhzhair/accesslimit-spring-boot.git 注解@AccessLimit 实现接口防刷功能,在方法上的注解参数优先于类上 ...

  5. springboot项目实例_Springboot项目的接口防刷的实例

    今天跟大家分享Springboot项目的接口防刷的实例的知识. 1 Springboot项目的接口防刷的实例 说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考. 技术要点:spr ...

  6. Java接口防刷策略(自定义注解实现)

    前言 本文一定要看完,前部分为逻辑说明及简单实现,文章最后有最终版解决方案(基于lua脚本),因为前部分是防君子不防小人,无法抵挡for循环调用. 目的 短信发送及短信验证码校验接口防刷 一方面防止用 ...

  7. 优雅的接口防刷处理方案

    点击上方"Java基基",选择"设为星标" 做积极的人,而不是积极废人! 每天 14:00 更新文章,每天掉亿点点头发... 源码精品专栏 原创 | Java ...

  8. java接口防刷_API 接口防刷

    API 接口防刷 顾名思义,想让某个接口某个人在某段时间内只能请求N次. 在项目中比较常见的问题也有,那就是连点按钮导致请求多次,以前在web端有表单重复提交,可以通过token 来解决. 除了上面的 ...

  9. 【Java秒杀方案】11.功能开发-【商品秒杀及优化】防止超卖 接口优化(redis预减库存,内存标记减少redis访问,RabbitMQ异步下单) 安全优化(隐藏秒杀接口,验证码,接口防刷)

    商品秒杀核心功能及优化 1. 正常秒杀流程 在商品详情页面等待秒杀倒计时–http://localhost:8080/goodsDetail.htm?goodsId=2 倒计时为0,开始秒杀,点[秒杀 ...

最新文章

  1. Progressbar 实现从右向左 加载(逆向)
  2. Python的__getattr__方法学习
  3. animate 实现滑动切换效果
  4. transactionManager 以及datasource type解析
  5. java8泛型包括_JAVA8 获取泛型类型问题
  6. Ubuntu MySQL 重新安装
  7. Spring延迟依赖注入ObjectFactory/ObjectProvider
  8. springboot如何使用多线程,线程池管理
  9. UVA260 Il Gioco dell‘X【DFS】
  10. Bootstrap 后台模板-AdminLTE
  11. PHP接入芝麻信用续。
  12. 机器学习LDA——实验报告
  13. c语言大作业图书馆,大一C语言课程设计—图书馆管理系统
  14. 越狱完发现bigboss源是空白
  15. GitLab合并出现 “Ready to be merged automatically” 提示
  16. 现代大学英语精读第二版(第四册)学习笔记(原文及全文翻译)——3A - Groundless Beliefs(无根据的信念)
  17. JS中Object.entries()方法
  18. 微信小程序学习第8天——自定义组件的数据监听器Observer小案例
  19. 逝去的岁月,回忆的青春
  20. jsp页面转换成html,jsp页面修改成html页面

热门文章

  1. 性能测试基本流程介绍(《软件性能测试过程详解与安全剖析》)
  2. SQL里的SWITCH分支语句
  3. hideprocess in bcb
  4. php输入对话框,如何使用JavaScript实现输入对话框
  5. js reduce实现中间件_js数组高阶方法reduce经典用法代码分享
  6. python中字典数据的特点_Python数据类型(字典)
  7. axios拦截器的实现
  8. 动手动脑 - 继承与多态
  9. CentOS 搭建 LAMP服务器
  10. 都江堰很美-佩服古人_Crmhf的一天