SpringBoot 使用注解解决接口防刷

AOP实现操作日志记录 一、设计:    操作日志记录 根据业务场景 一般是需要记录下数据修改更新的日志,查询类可以忽略。 所以需要对指定的某些方法进行记录。这块希望可以结合注解灵活操作,对于注解的方法进行日志记录操作日志表设计如下:CREATE TABLE `op_log` (  `id` bigint(20) NOT NULL COMMENT '主键',  `operator` varchar(32) NOT NUL... 阅读详情
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Prevent {
    int seconds() default 60;
    int maxCount() default 1;
    String message() default "";
}
import cn.hutool.json.JSONUtil;
import com.boot.common.BusinessException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * 防刷切面实现类
 */
@Aspect
@Component
public class PreventAop {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("@annotation(com.boot.aop.Prevent)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void joinPoint(JoinPoint joinPoint) throws Exception {
        String requestStr = JSONUtil.toJsonStr(joinPoint.getArgs()[0]);
        if (StringUtils.isEmpty(requestStr) || requestStr.equalsIgnoreCase("{}")) {
            throw new BusinessException("[防刷]入参不允许为空");
        }

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = joinPoint.getTarget().getClass().getMethod(methodSignature.getName(),
                methodSignature.getParameterTypes());

        Prevent preventAnnotation = method.getAnnotation(Prevent.class);
        String methodFullName = method.getDeclaringClass().getName() + method.getName();

        defaultHandle(requestStr, preventAnnotation, methodFullName);
    }

    private void defaultHandle(String requestStr, Prevent prevent, String methodFullName) throws Exception {
        String base64Str = toBase64String(requestStr);
        int expire = prevent.seconds();
        int maxCount = prevent.maxCount();
        String resp = redisTemplate.opsForValue().get(methodFullName + base64Str);
        int count = StringUtils.isEmpty(resp) ? 0 : Integer.parseInt(resp);
        if (StringUtils.isEmpty(resp)) {
            redisTemplate.opsForValue().set(methodFullName + base64Str, "1", expire, TimeUnit.SECONDS);
        } else if (count < maxCount) {
            redisTemplate.opsForValue().increment(methodFullName + base64Str);
        } else {
            String message = !StringUtils.isEmpty(prevent.message()) ? prevent.message() :
                    expire + "超出访问次数";
            throw new BusinessException(message);
        }
    }

    /**
     * 对象转换为base64字符串
     *
     * @param obj 对象值
     * @return base64字符串
     */
    private String toBase64String(String obj) throws Exception {
        if (StringUtils.isEmpty(obj)) {
            return null;
        }
        Base64.Encoder encoder = Base64.getEncoder();
        byte[] bytes = obj.getBytes(StandardCharsets.UTF_8);
        return encoder.encodeToString(bytes);
    }

}
/**
 * 基础响应码
 */
public class BusinessCode {
    //--------成功------------
    public static final BusinessCode SUCCESS = new BusinessCode("success", "操作成功");

    //--------失败------------
    public static final BusinessCode FAIL = new BusinessCode("fail", "系统异常");
    public static final BusinessCode EXCEPTION = new BusinessCode("exception", "未知异常");
    public static final BusinessCode PARAM_ILLEGAL = new BusinessCode("param_illegal", "参数不合法");
    public static final BusinessCode PARAM_EMPTY = new BusinessCode("param_empty", "入参为空");

    private String code;

    private String msg;


    public BusinessCode(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public BusinessCode(BusinessCode businessCode) {
        this.code = businessCode.getCode();
        this.msg = businessCode.getMsg();
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}
/**
 * 基础业务异常类
 */
public class BusinessException extends RuntimeException{
    private String code;
    private String msg;
    private Throwable cause;
    public BusinessException(){

    }

    public BusinessException(String msg) {
        super(msg);
        this.setCode(BusinessCode.FAIL.getCode());
        this.setMsg(msg);
    }

    public BusinessException(BusinessCode businessCode) {
        super(businessCode.getMsg());
        this.setCode(businessCode.getCode());
        this.setMsg(businessCode.getMsg());
    }

    public BusinessException(String msg, Throwable e) {
        super(msg);
        this.setCode(BusinessCode.FAIL.getCode());
        this.setMsg( msg);
        this.cause = e;
    }

    public BusinessException(BusinessCode businessCode, String msg) {
        super(msg);
        this.setCode(businessCode.getCode());
        this.setMsg(msg);
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public Throwable getCause() {
        return cause;
    }
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局异常捕获
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 入参非法异常捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler({BusinessException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handleServiceException(BusinessException e) {
        log.error("系统异常", e);
        BusinessCode code = new BusinessCode(e.getCode(), e.getMsg());
        return Response.fail(code, e.getMsg());
    }


    /**
     * 系统异常捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handleOtherException(Exception e) {
        log.error("系统异常", e);
        return Response.fail(BusinessCode.EXCEPTION, "系统异常");
    }

}
import java.io.Serializable;

/**
 * 返回数据
 */
public class Response<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 响应业务状态
     */
    private String code;

    /**
     * 响应消息
     */
    private String msg;

    /**
     * 响应中的数据
     */
    private transient T data;

    private Response() {
    }

    public Response(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static Response init(BusinessCode respCode, String msg) {
        Response response = new Response();
        response.setCode(respCode.getCode());
        response.setMsg(msg);
        return response;
    }

    public static <T> Response init(BusinessCode respCode, String msg, T data) {
        Response response = new Response();
        response.setCode(respCode.getCode());
        response.setMsg(msg);
        response.setData(data);
        return response;
    }

    public static <T> Response init(String code, String msg, T data) {
        Response response = new Response();
        response.setCode(code);
        response.setMsg(msg);
        response.setData(data);
        return response;
    }

    public static Response success() {
        return init(BusinessCode.SUCCESS, BusinessCode.SUCCESS.getMsg());
    }

    public static Response success(String msg) {
        return init(BusinessCode.SUCCESS, msg);
    }

    public static Response success(Object data, String msg) {
        return init(BusinessCode.SUCCESS, msg, data);
    }

    public static Response fail(BusinessCode respCode, String msg) {
        return init(respCode, msg);
    }

    public static Response fail() {
        return init(BusinessCode.FAIL, BusinessCode.FAIL.getMsg());
    }

    public static Response fail(String msg) {
        return init(BusinessCode.FAIL, msg);
    }

    public static boolean isSuccess(Response response) {
        return BusinessCode.SUCCESS.getCode() == response.getCode();
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

import com.boot.aop.Prevent;
import com.boot.common.Response;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 切面实现入参校验
 */
@RestController
public class MyController {

    @GetMapping(value = "/testPrevent")
    @Prevent(maxCount = 5)
    public Response testPrevent(String mobile) {
        return Response.success("调用成功");
    }

}

一个注解搞定 Spring Boot 接口防刷

SpringBoot实现接口防刷的5种高效方案详解 在当今互联网应用中,接口安全是系统设计中不可忽视的重要环节。恶意用户或自动化脚本的高频请求不仅会消耗宝贵的服务器资源,还可能导致数据异常、服务不可用甚至系统崩溃。本文将详细介绍在SpringBoot框架下实现接口防刷的5种技术方案,帮助开发者构建更加健壮的应用系统。本文详细介绍了SpringBoot框架下5种接口防刷方案,从简单的注解限流到复杂的Sentinel集成,开发者可以根据实际需求选择合适的方案。在实际项目中,通常需要组合多种方案来构建全方位的防护体系。技术选型关键点评估系统规模(单机/分布式) 阅读详情

相关推荐

springboot项目api防刷

aop+redis实现ip请求方法防刷 引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-...

weixin_45052750的博客 1797

Spring boot 对外接口API通过AOP防刷

Spring boot 对外接口API通过AOP防刷pom.xmlAOP自定义注解类AOP切面业务类redis序列化配置RedisSerializerConfig限流测试类启动类配置文件application.yml spring boot 项目对外提供接口防刷功能,通过自定义注解,拦截接口,设置接口在规定的时间内请求的次数,该方式定义的自定义注解只适用在方法上,不能使用在类上。 pom.xml <?xml version="1.0" encoding="UTF-8"?> <proje

lakelise的专栏 718

Frida+Objection保姆级教程:从环境搭建到实战Hook(含Wallbreaker插件使用)

本文提供了一份从零开始的Frida与Objection移动安全动态分析实战指南。详细讲解了Python环境配置、Frida-Server部署、Objection核心命令使用以及Wallbreaker插件安装与应用。通过实战案例演示如何Hook网络请求(如HttpURLConnection和OkHttp3),帮助安全研究人员快速掌握应用运行时行为分析与漏洞挖掘技能。

weixin_28318011的博客 101

【huTool】真的好用,面对接口开发之再来一弹

小公司的悲哀,维护项目和小需求不断。。 整理一下,算作纪念 需求:第三方需要接口传输图片流到特定的摄像头下 分析: /** * 开发接口: * 1.接收主要:图片(小图,大图),时间,设备id -> Base64(小图,大图),时间戳,设备id * 2.调用平台登录,全部相机接口 -> 相机集合[相机id,相机唯一标识] * 3.遍历相机集合根据【设备id = 唯一标识】锁定入参:[相机id,Base64(小图,大图),时间戳] * 4.调用入库接口,传入入参 * 5.异常

weixin_44481081的博客 2644

AMD Ross FPGA Agent 实战:用 AI 驱动 Vivado 开发流程

在 EDA 领域,FPGA 开发长期面临工具链重、反馈周期长、报错晦涩等痛点。AI Agent 通过自然语言交互与工具调用,将 Vivado 的 Tcl 批处理流程封装为可编排、可观测的智能体,显著降低查文档与读报告的时间成本。其核心在于 Harness 与 Agent 的协同:Harness 提供安全执行环境,Agent 负责决策与迭代。典型应用包括工程创建、约束生成、综合实现报告解读及比特流失败排查。本文以 AMD Ross 为例,拆解其架构设计与实操方法,帮助开发者理解如何将 Agent 落地到高门槛

weixin_29189363的博客 1024

单反相机物镜设计[DG-10]

REAR(要打在像面,操作数要找像面对应位置15):以透镜单位表示的真实光线径向坐标,波长由Wave定义,参见“Hx、Hy、Px和Py”。最小玻璃厚度最小不能小于semi-dia的1/10,要根据layout看有没有过厚过薄,反复调节。PROD:两个操作数的乘积(操作#1 X操作#2)。3x4就是57.3x0.41=23.5。拦光一般在第一面和最后一面操作,减少边缘无用光线。光阑面与镜面贴近,要调距离,同时设置光阑像差。后截距是指从镜头后表面到焦点的距离。CONS:弧度转为角度。镜头相互嵌入,有错误。

weixin_72050316的博客 600

springboot实现防重复提交和防重复点击

背景 同一条数据被用户点击了多次,导致数据冗余,需要防止弱网络等环境下的重复点击 目标 通过在指定的接口处添加注解,实现根据指定的接口参数来防重复点击 说明 这里的重复点击是指在指定的时间段内多次点击按钮 技术方案 springboot + redis锁 + 注解 使用 feign client 进行请求测试 最终的使用实例 1、根据接口收到 PathVariable 参数判断唯一 /*...

DaleyZou的博客 1241

广义正态分布优化算法(GNDO)详解:从理论到实践

广义正态分布优化算法(GNDO)是一种基于正态分布理论的新型元启发式优化算法。该算法通过局部开发和全局探索两种策略平衡搜索过程:局部开发利用广义平均位置和标准差进行精细搜索,而全局探索通过随机个体信息共享扩大搜索范围。GNDO具有参数少、结构简单、收敛速度快等优点,在光伏模型参数提取等工程优化问题中表现优异。算法将种群位置更新与正态分布参数调整相联系,通过自适应机制平衡探索与开发,数学分析表明其具有全局收敛性。相比传统优化算法,GNDO在探索能力和开发能力上均有优势,是高维复杂优化问题的有效解决方案。

qq_42212808的博客 138

java 接口防刷_Springboot项目的接口防刷(实例)

importcom.alibaba.fastjson.JSON;importcom.example.demo.action.AccessLimit;importcom.example.demo.redis.RedisService;importcom.example.demo.result.CodeMsg;importcom.example.demo.result.Result;importorg...

weixin_30114649的博客 258

OpenFeign整合Sentinel实现熔断降级

常用于实现熔断降级的框架有Hystrix、Sentinel,我们常说的Spring Cloud项目说的其实是Spring Cloud Netflix,Hystrix以及前面学习过的Ribbon都是Netflix系的家族成员,所以使用Hystrix可以非常简单的与当前项目中使用到的OpenFeign、Ribbon整合,但笔者并没有选择Hystrix,而是选择阿里系的Sentinel。 为什么选择Sentinel而不是Hystrix?从接入简单考虑可能选择Hystrix是不错的选择,但笔者对Hyst...

吴就业 6718

白鲸优化算法(BWO)详解:从生物灵感 to 工程实践

白鲸优化算法(BWO)是一种新型的群体智能优化算法,模拟白鲸的游泳、捕食和鲸落行为。该算法通过平衡因子控制探索与开发阶段的转换:探索阶段采用正弦/余弦函数模拟白鲸的同步游泳,开发阶段引入莱维飞行增强局部搜索,鲸落阶段通过随机更新避免局部最优。BWO具有参数少、实现简单、收敛速度快等优点,已在多个优化问题上展现出优异性能。其数学模型将白鲸的三种核心行为抽象为位置更新公式,实现了全局搜索与局部开发的自然平衡。

qq_42212808的博客 290

SpringBoot一个注解,实现接口防刷

定义一切面,通过@Prevent注解作为切入点、在该切面的前置通知获取该方法的所有入参并将其Base64编码,将入参Base64编码+完整方法名作为redis的key,入参作为reids的value,@Prevent的value作为redis的expire,存入redis;

Lyq2017901206的博客 235

龙芯2K1000 OTG双模驱动深度解析

是Synopsys公司开发的USB 2.0 OTG控制器IP核,龙芯2K1000内置该IP,作为唯一的OTG控制器(PCI Dev4 Func0),物理基地址0x40000000。核心能力:同时支持Host主机模式(接U盘/键盘)、Device设备模式(虚拟串口ttyGS0)、OTG双模自动切换速率驱动路径:内核源码PMON:启用otg0设备树内核:开启HOSTPERIPHERALG_SERIAL启动参数脚本:sysfs角色切换+开机自启Host按以上配置,龙芯2K1000 DWC2 OTG可完美实现。

weixin_44932366的博客 376

springboot 获取登录浏览器_Spring Boot 项目的 API 如何去接口防刷

•首先是写一个注解类•拦截器中实现•注册到springboot中•在Controller中加入注解说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考 一,技术要点:springboot的基本知识,redis基本操作,首先是写一个注解类:import java.lang.annotation.Retention;import java.lang.annotation.Target...

weixin_39716264的博客 150

【Bug已解决】openclaw max turns reached / Tool calls exceeded limit — OpenClaw 最大轮次超限解决方案

OpenClaw 在执行过程中达到最大轮次限制任务未完成,本质是 --max-turns 设置过小或任务过于复杂。文中给出增加轮次、--continue 继续、分步执行等完整方案。

一键难忘的博客 5505

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

优雅的接口防刷处理方案

以前其实对注解 + 反射其实有点不太懂干嘛用的,而从之前的数据报表导出,再到基本权限控制实现,最后到今天的【接口防刷】一点点来进步去补充自己的知识点,而且,感觉写博客真的是件挺有意义的事情,它会让你去更深入的了解某个点,并且知识是相关联的,探索的过程中会牵扯到其他别的知识点,就像之前的写的【单例模式】实现,一开始就了解到懒汉式,饿汉式。嗯,现在看起来,可以针对每个要进行防刷处理的接口进行针对性自定义多长时间内的最大访问次数,以及禁用时长,哪个接口需要,就直接+在那个接口方法出即可。

竹林幽深 286

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

帮我写一个springboot接口防刷的切面和注解实现

好的,为了实现 Spring Boot 接口防刷的切面和注解,您需要执行以下步骤: 在您的 Spring Boot 应用中创建一个切面类。在该类中,您可以使用 @Aspect 注解声明它是一个切面。 在切面类中创建一个方法,使用 @Around 注解声明它是一个环绕通知方法。环绕通知方法可以在目标方法执行前后执行指定的代码。 在环绕通知方法中,使用 @Pointcut 注解声明切点,并使用 ...

weixin_35751412的博客 82

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

springboot 获取登录浏览器_Spring Boot 项目的 API 接口防刷

首先是写一个注解类拦截器中实现注册到springboot中在Controller中加入注解《Java 2019 超神之路》《Dubbo 实现原理与源码解析 —— 精品合集》《Spring 实现原理与源码解析 —— 精品合集》《MyBatis 实现原理与源码解析 —— 精品合集》《Spring MVC 实现原理与源码解析 —— 精品合集》《Spring Boot 实现原理与源码解析 —— 精品合集》...

weixin_39675926的博客 399

一个注解搞定 SpringBoot 接口防刷,还有谁不会?

作者:CS打赢你blog.youkuaiyun.com/weixin_42533856/article/details/82593123说明:使用了注解的方式进行对接口防刷的功能,非常高大上,本文章仅供参考一,技术要点:springboot的基本知识,redis基本操作,首先是写一个注解类:importjava.lang.annotation.Retention; importj...

WantFlyDaCheng的博客 236

一个注解搞定 SpringBoot 接口防刷,真香!

大家好,我是猿人(猿码天地创始人),今天给大家聊聊接口防刷的那些事。接口防刷,顾名思义,想让某个接口某个人在某段时间内只能请求N次,或者某个接口对外在某一段时间内只允许访问N次。在项目中比...

猿码天地 4172

springboot接口防刷实现

本文主要介绍一种通过实现自定义注解,实现一种比较通用的接口防刷方式

Terry Tian' coding Life 1817

【后端分享】SpringBoot实现接口防刷的5种实现方案!

创建一个Redis限流的Lua脚本,放在resources目录下的。

weixin_60937489的博客 1978

【Springboot之切面编程】注解实现接口防刷

来源:https://www.jianshu.com/p/697f1c5eaa3f?utm_campaign=haruki&amp;utm_content=note&amp;utm_medium=reader_share&amp;utm_source=qq 本文介绍一种极简洁、灵活通用接口防刷实现方式、通过在需要防刷的方法加上@Prevent 注解即可实现短信防刷; 使用方式大致如下: ...

rentian1的博客 1416

SpringBoot接口防刷

SpringBoot接口防刷 API 接口防刷 顾名思义,想让某个接口某个人在某段时间内只能请求N次。 在项目中比较常见的问题也有,那就是连点按钮导致请求多次,以前在web端有表单重复提交,可以通过token 来解决。 除了上面的方法外,前后端配合的方法。现在全部由后端来控制。 原理 在你请求的时候,服务器通过redis 记录下你请求的次数,如果次数超过限制就不给访问。 在redis 保存的key 是有时效性的,过期就会删除。 代码实现: 为了让它看起来逼格高一点,所以以自定义注解的方式实现 @Reques

YSecret_Y的博客 1858
上一篇: Java开发 之从Spring容器相关操作
下一篇: SpringCloud 之OpenFeign超时详解
yyangqqian
博客等级 码龄15年 406粉丝 406原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值