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

首先是写一个注解类:

  1. import java.lang.annotation.Retention;
  2. import java.lang.annotation.Target;
  3.  
  4. import static java.lang.annotation.ElementType.METHOD;
  5. import static java.lang.annotation.RetentionPolicy.RUNTIME;
  6.  
  7. /**
  8. * @author yhq
  9. * @date 2018/9/10 15:52
  10. */
  11.  
  12. @Retention(RUNTIME)
  13. @Target(METHOD)
  14. public @interface AccessLimit {
  15.  
  16. int seconds();
  17. int maxCount();
  18. boolean needLogin()default true;
  19. }

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

  1. import com.alibaba.fastjson.JSON;
  2. import com.example.demo.action.AccessLimit;
  3. import com.example.demo.redis.RedisService;
  4. import com.example.demo.result.CodeMsg;
  5. import com.example.demo.result.Result;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Component;
  8. import org.springframework.web.method.HandlerMethod;
  9. import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
  10.  
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import java.io.OutputStream;
  14.  
  15. /**
  16. * @author yhq
  17. * @date 2018/9/10 16:05
  18. */
  19.  
  20. @Component
  21. public class FangshuaInterceptor extends HandlerInterceptorAdapter {
  22.  
  23. @Autowired
  24. private RedisService redisService;
  25.  
  26. @Override
  27. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  28.  
  29. //判断请求是否属于方法的请求
  30. if(handler instanceof HandlerMethod){
  31.  
  32. HandlerMethod hm = (HandlerMethod) handler;
  33.  
  34. //获取方法中的注解,看是否有该注解
  35. AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
  36. if(accessLimit == null){
  37. return true;
  38. }
  39. int seconds = accessLimit.seconds();
  40. int maxCount = accessLimit.maxCount();
  41. boolean login = accessLimit.needLogin();
  42. String key = request.getRequestURI();
  43. //如果需要登录
  44. if(login){
  45. //获取登录的session进行判断
  46. //.....
  47. key+=""+"1"; //这里假设用户是1,项目中是动态获取的userId
  48. }
  49.  
  50. //从redis中获取用户访问的次数
  51. AccessKey ak = AccessKey.withExpire(seconds);
  52. Integer count = redisService.get(ak,key,Integer.class);
  53. if(count == null){
  54. //第一次访问
  55. redisService.set(ak,key,1);
  56. }else if(count < maxCount){
  57. //加1
  58. redisService.incr(ak,key);
  59. }else{
  60. //超出访问次数
  61. render(response,CodeMsg.ACCESS_LIMIT_REACHED); //这里的CodeMsg是一个返回参数
  62. return false;
  63. }
  64. }
  65.  
  66. return true;
  67.  
  68. }
  69. private void render(HttpServletResponse response, CodeMsg cm)throws Exception {
  70. response.setContentType("application/json;charset=UTF-8");
  71. OutputStream out = response.getOutputStream();
  72. String str = JSON.toJSONString(Result.error(cm));
  73. out.write(str.getBytes("UTF-8"));
  74. out.flush();
  75. out.close();
  76. }
  77. }

再把Interceptor注册到springboot中

  1. import com.example.demo.ExceptionHander.FangshuaInterceptor;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  6.  
  7. /**
  8. * @author yhq
  9. * @date 2018/9/10 15:58
  10. */
  11. @Configuration
  12. public class WebConfig extends WebMvcConfigurerAdapter {
  13.  
  14. @Autowired
  15. private FangshuaInterceptor interceptor;
  16.  
  17. @Override
  18. public void addInterceptors(InterceptorRegistry registry) {
  19. registry.addInterceptor(interceptor);
  20. }
  21. }

接着在Controller中加入注解

  1. import com.example.demo.result.Result;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.ResponseBody;
  5.  
  6. /**
  7. * @author yhq
  8. * @date 2018/9/10 15:49
  9. */
  10.  
  11. @Controller
  12. public class FangshuaController {
  13.  
  14. @AccessLimit(seconds=5, maxCount=5, needLogin=true)
  15. @RequestMapping("/fangshua")
  16. @ResponseBody
  17. public Result<String> fangshua(){
  18.  
  19. return Result.success("请求成功");
  20.  
  21. }

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

本人免费整理了Java高级资料,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo高并发分布式等教程,一共30G,需要自己领取。
传送门:https://mp.weixin.qq.com/s/osB-BOl6W-ZLTSttTkqMPQ

Springboot项目的接口防刷(实例)的更多相关文章

  1. [转]Springboot项目的接口防刷的实例

    来源:微信公众号 马士兵 原地址:https://mp.weixin.qq.com/s/tHQcWwIt4c41IUnvCQ2QWA 说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供 ...

  2. Spring Boot项目的接口防刷

    说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考 一,技术要点:springboot的基本知识,redis基本操作, 首先是写一个注解类: import java.lang.an ...

  3. 使用JWT设计SpringBoot项目api接口安全服务

    转载直: 使用JWT设计SpringBoot项目api接口安全服务

  4. 使用Redis+自定义注解实现接口防刷

    最近开发了一个功能,需要发送短信验证码鉴权,考虑到短信服务需要收费,因此对此接口做了防刷处理,实现方式主要是Redis+自定义注解(需要导入Redis的相关依赖,完成Redis的相关配置,gs代码,这 ...

  5. Spring Boot 项目的 API 接口防刷

    首先是写一个注解类 拦截器中实现 注册到springboot中 在Controller中加入注解 说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考 一,技术要点:springbo ...

  6. springboot项目中接口入参的简单校验

    .katex { display: block; text-align: center; white-space: nowrap; } .katex-display > .katex > ...

  7. 页面接口防刷 解决思路一nginx

    线上环境 很多接口 如果不做缓存 可能导致有人拿到url  每秒几万次的访问后台程序,导致系统down机. 此处, nginx可以加一层缓存. expires起到控制页面缓存的作用,合理的配置expi ...

  8. spring中实现基于注解实现动态的接口限流防刷

    本文将介绍在spring项目中自定义注解,借助redis实现接口的限流 自定义注解类 import java.lang.annotation.ElementType; import java.lang ...

  9. docker安装部署、fastDFS文件服务器搭建与springboot项目接口

    一.docker安装部署 1.更新yum包:sudo yum update 2.安装需要的软件包,yum-util 提供yum-config-manager功能,另外两个是devicemapper驱动 ...

随机推荐

  1. JQuery DOM操作:设置内容&属性&添加元素&插入元素&包裹&克隆&移除&替换

    JQuery text().html().val() $(elem).text(str):添加文本内容str到elem类型元素,返回jQuery对象 $(elem).text():返回第一个elem标 ...

  2. 19 JavaScript数组 &数组增删&最值&排序&迭代

    关联数组(散列) 关联数组又叫做散列,即使用命名索引. JavaScript数组只支持数字索引. JavaScript对象使用命名索引,而数组使用数字索引,JavaScript数组是特殊类型的对象. ...

  3. 吴裕雄 python 神经网络——TensorFlow 数据集基本使用方法

    import tempfile import tensorflow as tf input_data = [1, 2, 3, 5, 8] dataset = tf.data.Dataset.from_ ...

  4. Cisco Umbrella WLAN

    Cisco Umbrella WLAN在域名系统(DNS)级别提供云交付网络安全服务,可自动检测已知和紧急威胁. 此功能允许您在实际恶意攻击之前阻止托管恶意软件,僵尸网络和网络钓鱼的站点. Cisco ...

  5. Python笔记⑤爬虫

    爬虫的前奏 # 爬虫前奏 # 明确目的 # 找到数据对应的网页 # 分析网页的结果找到数据所在的标签位置 # 模拟HTTP请求,向服务器发送这个请求,获取到服务器返回给我们的HTML # 用正则表达式 ...

  6. SpringBoot启动使用elasticsearch启动异常:Received message from unsupported version:[2.0.0] minimal compatible

    SpringBoot启动使用elasticsearch启动异常:Received message from unsupported version:[2.0.0] minimal compatible ...

  7. .NET Runtime at IP 791F7E06 (79140000) with exit code 80131506.

    事件類型: 錯誤 事件來源: .NET Runtime 事件類別目錄: 無 事件識別碼: 1023 日期: 2015/12/15 時間: 上午 10:18:52 使用者: N/A 電腦: KM-ERP ...

  8. idea设置代码提示忽略大小写

  9. uniGUI之UniSyntaxEdit(24)

    UniSyntaxEdit1语法高亮显示控件,主要属性Language,它是  多行 1]Language 语言 2]执行 FDquery1.Open(UniSyntaxEdit1.Lines.Tex ...

  10. python3.6.5修改print的颜色

    开头部分:\033[显示方式;前景色;背景色m +想要输出的内容:\033[0m      注意:开头部分的三个参数:显示方式,前景色,背景色是可选参数,具体参数效果见下文,可以只写其中的某一个:参数 ...