技术要点: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项目的接口防刷(实例)的更多相关文章

  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. SSH 维持权限(好用)

    很多时候我们拿下机器后需要维持权限,在计划任务上加入定时反弹shell这很容易被 运维人员发现,有些场景没必要用到rootkit级别的后门,我们可以尝试使用ssh后门 1.目的 长期维持机器root权 ...

  2. Many Formulas

    You are given a string S consisting of digits between 1 and 9, inclusive. You can insert the letter ...

  3. jquery 分页 Ajax异步

    //使用Ajax异步查询数据 <div class="table-responsive"> <table class="table table-bord ...

  4. 洛谷 P5057 [CQOI2006]简单题(树状数组)

    嗯... 题目链接:https://www.luogu.org/problem/P5057 首先发现这道题中只有0和1,所以肯定与二进制有关.然后发现这道题需要支持区间更改和单点查询操作,所以首先想到 ...

  5. 动态代理Cglib

    jar包 <!-- https://mvnrepository.com/artifact/cglib/cglib --><dependency> <groupId> ...

  6. 汇编语言从入门到精通-5微机CPU的指令系统1

    微机CPU的指令系统 5.1 汇编语言指令格式 为了介绍指令系统中指令的功能,先要清楚汇编语言是如何书写指令的,这就象在学习高级语言程序设计时,要清楚高级语言语句的语义.语法及其相关规定一样. 5.1 ...

  7. Linux环境查看Java应用消耗资源情况

    linux线上资源耗时定位 https://www.cnblogs.com/wuchanming/p/7766994.html 1. jps -ml 查看服务器上运行的Java程序 2. jmap 查 ...

  8. Linux命令:netstat命令

    netstat功能:显示网络连接情况 netstat功能选项 -t:tcp协议的连接 -u:udp协议的链接 -l:监听状态的连接 -a:所有状态的连接 -p:连接相关的进程 -n:数字格式显示 -r ...

  9. thymeleaf 学习笔记(转)

    原文:http://blog.csdn.net/pdw2009/article/details/44410659 thymeleaf,我个人认为是个比较好的模板,性能也比一般的,比如freemaker ...

  10. Linux centosVMware Linux集群架构LVS DR模式搭建、keepalived + LVS

    一.LVS DR模式搭建 三台机器 分发器,也叫调度器(简写为dir) davery :1.101 rs1 davery01:1.106 rs2 davery02:11.107 vip 133.200 ...