Spring Boot 项目的 API 接口防刷
首先是写一个注解类
拦截器中实现
注册到springboot中
在Controller中加入注解
说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考 一,技术要点: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;
}拦截器
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();
}
}注册到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("请求成功"); }
Spring Boot 项目的 API 接口防刷的更多相关文章
- Spring Boot项目的Logback配置文件使用yaml格式
1.普通的Spring项目使用logback默认用properties文件做为配置变量. 2.如果非要用yaml文件,那么可以转成Spring Boot项目,天生无缝结合 3.没办法,如果项目配置文件 ...
- 一行配置搞定 Spring Boot项目的 log4j2 核弹漏洞!
相信昨天,很多小伙伴都因为Log4j2的史诗级漏洞忙翻了吧? 看到群里还有小伙伴说公司里还特别建了800+人的群在处理... 好在很快就有了缓解措施和解决方案.同时,log4j2官方也是速度影响发布了 ...
- 提升Spring Boot项目中API接口并发能力的一个注解,效果明显
异步调用几乎是处理高并发Web应用性能问题的万金油,那么什么是"异步调用"?"异步调用"对应的是"同步调用",同步调用指程序按照定义顺序依次 ...
- spring boot项目的maven库查询地址
阿里巴巴地址 http://maven.aliyun.com/nexus/#welcome maven通用地址 http://mvnrepository.com/ gradle默认mavenCentr ...
- Spring Boot实现通用的接口参数校验
Spring Boot实现通用的接口参数校验 Harries Blog™ 2018-05-10 2418 阅读 http ACE Spring App API https AOP apache IDE ...
- Spring Boot Hello World (restful接口)例子
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- 使用Redis+自定义注解实现接口防刷
最近开发了一个功能,需要发送短信验证码鉴权,考虑到短信服务需要收费,因此对此接口做了防刷处理,实现方式主要是Redis+自定义注解(需要导入Redis的相关依赖,完成Redis的相关配置,gs代码,这 ...
- Spring Boot项目的接口防刷
说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考 一,技术要点:springboot的基本知识,redis基本操作, 首先是写一个注解类: import java.lang.an ...
- swagger ui和spring boot集成生成api文档
作者:小莫链接:https://www.zhihu.com/question/28119576/answer/134580038来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...
随机推荐
- linux 用户操作命令
今日思语:看到优秀的人还那么努力,你是否会眼馋~ linux系统上经常会对用户进行一些相关操作,像新增.修改.删除用户等操作. 1.新增用户 useradd 选项 用户 参数说明: • 选项: • - ...
- RFM模型的变形LRFMC模型与K-means算法的有机结合
应用场景: 可以应用在不同行业的客户分类管理上,比如航空公司,传统的RFM模型不再适用,通过RFM模型的变形LRFMC模型实现客户价值分析:基于消费者数据的精细化营销 应用价值: LRFMC模型构建之 ...
- 洛谷P4170 [CQOI2007]涂色题解
废话: 这个题我第一眼看就是贪心呐, 可能是我之前那做过一道类似的题这俩题都是关于染色的 现在由于我帅气无比的学长的指导, 我已经豁然开朗, 这题贪心不对啊, 当时感觉自己好厉害贪心都能想出来 差点就 ...
- Markdown&Latex学习笔记,qwq
目录 推荐的文章 居中 字体 加颜色 指数 分数 根号 神奇的符号(不要多想qwq) 箭头 小于号 大括号 累加符号 累乘符号 下标 \(\phi\)&\(\varphi\) \(\equiv ...
- 实验1c语言开发环境使用和数据类型,运算符和表达式
/*this is first c program*/ # include<stdio.h> int main() { printf("Hello Mars!"); ; ...
- python3-django+uwsgi+supervisor+nginx跳坑指南(记录)
首先运行django项目:在项目目录内: python manage.py runserver 0.0.0.0:8000 外部服务器访问:http://www.xxx.com:8000/ 可以正常运行 ...
- Morpheus
https://software.broadinstitute.org/morpheus/
- vue自定义指令导致的内存泄漏问题解决
vue的自定义指令是一个比较容易引起内存泄漏的地方,原因就在于指令通常给元素绑定了事件,但是如果忘记了解绑,就会产生内存泄漏的问题. 看下面代码: directives: { scroll: { in ...
- hive函数 get_json_object
pandas和SQL数据分析实战 https://study.163.com/course/courseMain.htm?courseId=1006383008&share=2&sha ...
- Django入门3 简单留言板项目案例及mysql驱动的安装配置
新建jangostart项目 使用manager.py新建app即单独的应用 创建一个message应用 manage.py@djangostart > startapp message 如果a ...