Springboot项目的接口防刷(实例)
技术要点: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
*/ @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; /**
* @author yhq
* @date 2018/9/10 15:58
*/
@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; /**
* @author yhq
* @date 2018/9/10 15:49
*/ @Controller
public class FangshuaController { @AccessLimit(seconds=5, maxCount=5, needLogin=true)
@RequestMapping("/fangshua")
@ResponseBody
public Result<String> fangshua(){ return Result.success("请求成功"); }
本文有参考其他视频的教学,希望可以帮助更多热爱it行业的人。
本人免费整理了Java高级资料,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo高并发分布式等教程,一共30G,需要自己领取。
传送门:https://mp.weixin.qq.com/s/osB-BOl6W-ZLTSttTkqMPQ
Springboot项目的接口防刷(实例)的更多相关文章
- [转]Springboot项目的接口防刷的实例
来源:微信公众号 马士兵 原地址:https://mp.weixin.qq.com/s/tHQcWwIt4c41IUnvCQ2QWA 说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供 ...
- Spring Boot项目的接口防刷
说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考 一,技术要点:springboot的基本知识,redis基本操作, 首先是写一个注解类: import java.lang.an ...
- 使用JWT设计SpringBoot项目api接口安全服务
转载直: 使用JWT设计SpringBoot项目api接口安全服务
- 使用Redis+自定义注解实现接口防刷
最近开发了一个功能,需要发送短信验证码鉴权,考虑到短信服务需要收费,因此对此接口做了防刷处理,实现方式主要是Redis+自定义注解(需要导入Redis的相关依赖,完成Redis的相关配置,gs代码,这 ...
- Spring Boot 项目的 API 接口防刷
首先是写一个注解类 拦截器中实现 注册到springboot中 在Controller中加入注解 说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考 一,技术要点:springbo ...
- springboot项目中接口入参的简单校验
.katex { display: block; text-align: center; white-space: nowrap; } .katex-display > .katex > ...
- 页面接口防刷 解决思路一nginx
线上环境 很多接口 如果不做缓存 可能导致有人拿到url 每秒几万次的访问后台程序,导致系统down机. 此处, nginx可以加一层缓存. expires起到控制页面缓存的作用,合理的配置expi ...
- spring中实现基于注解实现动态的接口限流防刷
本文将介绍在spring项目中自定义注解,借助redis实现接口的限流 自定义注解类 import java.lang.annotation.ElementType; import java.lang ...
- docker安装部署、fastDFS文件服务器搭建与springboot项目接口
一.docker安装部署 1.更新yum包:sudo yum update 2.安装需要的软件包,yum-util 提供yum-config-manager功能,另外两个是devicemapper驱动 ...
随机推荐
- 【代码总结】PHP面向对象之接口与多态性应用
概述: PHP之支持单继承,也就是说每个类智能继承一个父类.当声明的新类继承抽象类实现模板以后就不能再有其他问题,为了解决这个问题,PHP引用了接口 ------------------------- ...
- 吴裕雄 python 神经网络——TensorFlow训练神经网络:MNIST最佳实践
import os import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_N ...
- ipfs 资料汇集
目录 js ipfs u can use wikipeida here js ipfs https://github.com/ipfs/js-ipfs u can use wikipeida here ...
- Python中的代码块及其缓存机制、深浅copy
一.代码块及其缓存机制 代码块 一个模块.一个函数.一个类.一个文件等都是一个代码块:交互式命令下,一行就是一个代码块. 同一个代码块内的缓存机制(字符串驻留机制) 机制内容:Python在执行同一个 ...
- 【SSM sql.xml】日志查询mapper.xml
LogInfoMapper.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapp ...
- 与英特尔分道扬镳,苹果的5G业务掉队了吗?
5G概念已经大热,越来越多的厂商推出相关产品,中国骄傲之华为不仅在5G通信标准制定方面参与感非常强,也先于竞争对手推出5G智能终端,连同三星/Vivo等也纷纷推出5G终端,而作为智能手机市场绝对的利润 ...
- web优化(一 前端)
当我们在浏览器地址栏中输入一个URL的时候,网页开始请求,我们在页面上看到的内容就是许多个HTTP请求从服务器返回的数据展示,这些展示的快慢很大程度依赖前端的优化,怎样做好前端的优化,我这里总结了几点 ...
- linux文件或目录属性
wc(word count)命令的功能:统计指定文件的字节数.字数.行数.,并将统计结果显示输出 命令参数: -c 只显示字节数 -l 只显示行数 -w 只显示字数 od命令:查看二进制文件信息 ...
- C/C++网络编程6——实现基于UDP的服务器端/客户端
通过前面几节的内容,我们已经可以实现基本的C/S结构的程序了,但是当多个客户端同时向服务器端请求服务时,服务器端只能按顺序一个一个的服务,这种情况下,客户端的用户是无法忍受的.所以虚实现并发的服务器端 ...
- 创建SSH keys用于添加到Git服务器上
SSH keys SSH key 可以让你在你的电脑和Git服务器之间建立安全的加密连接.先执行以下语句来判断是否已经存在本地公钥: cat ~/.ssh/id_rsa.pub 如果你看到一长串以 s ...