来源:https://urlify.cn/ERf6Rr

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

技术要点: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;

/** * @author yhq * @date 2018/9/10 15:52 */

@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;

/** * @author yhq * @date 2018/9/10 16:05 */

@Componentpublic 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                 //加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;

/** * @author yhq * @date 2018/9/10 15:58 */@Configurationpublic 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;

/** * @author yhq * @date 2018/9/10 15:49 */

@Controllerpublic class FangshuaController {

    @AccessLimit(seconds=5, maxCount=5, needLogin=true)    @RequestMapping("/fangshua")    @ResponseBody    public Result fangshua(){return Result.success("请求成功");    }

本文有参考其他视频的教学,希望可以帮助更多热爱it行业的人。

(完)

  • Spring Boot + MyBatis + Druid + PageHelper 实现多数据源并分页

  • Spring Boot 多模块项目实践(附打包方法)

  • 一个女生不主动联系你还有机会吗?

  • 布隆过滤器实战!垃圾邮件识别?重复元素判断?缓存穿透?

(java思维导图)

长按关注,每天java一下,成就架构师

我就知道你在看!

springboot项目实例_Springboot项目的接口防刷(实例)相关推荐

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

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

  2. springboot接口防刷实现

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

  3. java抢购防止多次请求_springboot项目中接口防止恶意请求多次

    springboot项目中接口防止恶意请求多次 在项目中,接口的暴露在外面,很多人就会恶意多次快速请求,那我们开发的接口和服务器在这样的频率下的话,服务器和数据库很快会奔溃的,那我们该怎么防止接口防刷 ...

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

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

  5. Redis实现计数器---接口防刷---升级版(Redis+Lua)

    [前言] Cash Loan(一):Redis实现计数器---接口防刷  中介绍了项目中应用redis来做计数器的实现过程,最近自己看了些关于Redis实现分布式锁的代码后,发现在Redis分布式锁中 ...

  6. java接口防刷_API 接口防刷

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

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

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

  8. 创宇滤镜|API防刷|短信邮件接口防刷|验证码防刷|搜索防刷 - 知道创宇云安全

    创宇滤镜|API防刷|短信邮件接口防刷|验证码防刷|搜索防刷 - 知道创宇云安全 创宇滤镜|API防刷|短信邮件接口防刷|验证码防刷|搜索防刷 - 知道创宇云安全 posted on 2017-02- ...

  9. Redis限流接口防刷

    Redis限流接口防刷 Redis 除了做缓存,还能干很多很多事情:分布式锁.限流.处理请求接口幂等性...太多太多了- 大家好,我是llp,许久没有写博客了,今天就针对Redis实现接口限流做个记录 ...

最新文章

  1. 归并排序(代码注释超详细)
  2. 更换yum的源为阿里云或者网易
  3. Mybatis使用接口开发
  4. java list 去空字符串_【JAVA基础】list和字符串判空
  5. In Compiler.php line 36: Please provide a valid cache path.
  6. kong使用mysql_Kong官方文档翻译:安装Kong
  7. php form 上传_php+html5使用FormData对象提交表单及上传图片的方法
  8. tcp/ip协议初识
  9. 运动目标跟踪(二)--搜索算法预测模型之粒子滤波
  10. windows工具:推荐一款可以截长图(滚动截图)的工具FSCapture
  11. 为何国内“程序员”是秃头代名词?来看看国外程序员的一天
  12. 迅雷跃居全球BT市场第一
  13. 多线程程序的填坑笔记和多线程编程应该遵循的规则
  14. html5制作电子日历,基于HTML5的日历制作软件
  15. 【重磅】DeepMind开源史上最全强化学习框架OpenSpiel(附安装方法)
  16. java-net-php-python-jspm库存管理系统计算机毕业设计程序
  17. Android系统 小米/三星/索尼 应用启动图标未读消息数(BadgeNumber)动态提醒
  18. 【图像处理】基于matlab GUI多功能图像处理系统【含Matlab源码 1876期】
  19. xshell调用js脚本开发
  20. Jlink在ADS下的配置说明及常见问题解决办法

热门文章

  1. ubuntu 对apahce的php 服务器使用
  2. Excel中将一个表格的数据关联到另一个表格
  3. myeclipse-pro-2014-GA-offline-installer-windows 安装步骤 与安装效果预览
  4. PyTorch 系列教程之空间变换器网络
  5. OpenCV视频分析背景提取与前景提取
  6. 自动驾驶中的车道线跟踪技术
  7. 使用webpack构建多页应用
  8. 正面反击 Google、FB 等巨头,万维网之父携 Solid 归来
  9. ECS 备份数据到NAS(一):使用Windows Server Backup工具
  10. Android 网络编程系列(5)Volley 网络框架入门