位置: IT常识 - 正文

SpringBoot之用拦截器避免重复请求(springboot怎么配置拦截器)

编辑:rootadmin
开发中可能会经常遇到短时间内由于用户的重复点击导致几秒之内重复的请求,可能就是在这几秒之内由于各种问题,比如网络,事务的隔离性等等问题导致了数据的重复等问题,因此在日常开发中必须规避这类的重复请求操作,今天就用拦截器简单的处理一下这个问题。 ... 拦截器什么是拦截器

推荐整理分享SpringBoot之用拦截器避免重复请求(springboot怎么配置拦截器),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:springboot nio,springboot @lazy,springbootdao,springboot -d,springboot curd,springboot @lazy,springboot ci,springboot怎么用,内容如对您有帮助,希望把文章链接给更多的朋友!

Spring MVC中的拦截器(Interceptor)类似于Servlet中的过滤器(Filter),它主要用于拦截用户请求并作相应的处理。例如通过拦截器可以进行权限验证、记录请求信息的日志、判断用户是否登录等。

如何自定义拦截器

自定义一个拦截器非常简单,只需要实现HandlerInterceptor这个接口即可,这个接口有三个可实现的方法

preHandle()方法:该方法会在控制器方法前执行,其返回值表示是否知道如何写一个接口。中断后续操作。当其返回值为true时,表示继续向下执行;当其返回值为false时,会中断后续的所有操作(包括调用下一个拦截器和控制器类中的方法执行等)。

postHandle()方法:该方法会在控制器方法调用之后,且解析视图之前执行。可以通过此方法对请求域中的模型和视图做出进一步的修改。

afterCompletion()方法:该方法会在整个请求完成,即视图渲染结束之后执行。可以通过此方法实现一些资源清理、记录日志信息等工作。

如何让拦截器在Spring Boot中生效

想要在Spring Boot生效其实很简单,只需要定义一个配置类,实现WebMvcConfigurer这个接口,并且实现其中的addInterceptors()方法即可,代码如下:

@Configurationpublic class WebConfig implements WebMvcConfigurer { @Autowired private XXX xxx; @Override public void addInterceptors(InterceptorRegistry registry) { // 不拦截的uri final String[] commonExclude = {}}; registry.addInterceptor(xxx).excludePathPatterns(commonExclude); }}用拦截器规避重复请求需求SpringBoot之用拦截器避免重复请求(springboot怎么配置拦截器)

开发中可能会经常遇到短时间内由于用户的重复点击导致几秒之内重复的请求,可能就是在这几秒之内由于各种问题,比如网络,事务的隔离性等等问题导致了数据的重复等问题,因此在日常开发中必须规避这类的重复请求操作,今天就用拦截器简单的处理一下这个问题。

思路

在接口执行之前先对指定接口(比如标注某个注解的接口)进行判断,如果在指定的时间内(比如5秒)已经请求过一次了,则返回重复提交的信息给调用者。

根据什么判断这个接口已经请求了?

根据项目的架构可能判断的条件也是不同的,比如IP地址,用户唯一标识、请求参数、请求URI等等其中的某一个或者多个的组合。

这个具体的信息存放在哪?

由于是短时间内甚至是瞬间并且要保证定时失效,肯定不能存在事务性数据库中了,因此常用的几种数据库中只有Redis比较合适了。

实现Docker启动一个Redisdocker pull redis:7.0.4docker run -itd \--name redis \-p 6379:6379 \redis:7.0.4创建一个Spring Boot项目

使用idea的Spring Initializr来创建一个Spring Boot项目,如下图:

添加依赖

pom.xml文件如下

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>springboot_06</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot_06</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--spring redis配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <!-- 1.5的版本默认采用的连接池技术是jedis 2.0以上版本默认连接池是lettuce, 在这里采用jedis,所以需要排除lettuce的jar --> <exclusions> <exclusion> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </exclusion> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>配置Redis

application.properties

spring.redis.host=127.0.0.1spring.redis.database=1spring.redis.port=6379定义一个注解package com.example.springboot_06.intercept;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface RepeatSubmit { /** * 默认失效时间5秒 * * @return */ long seconds() default 5;}创建一个拦截器package com.example.springboot_06.intercept;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.annotation.AnnotationUtils;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.Objects;import java.util.concurrent.TimeUnit;/** * 重复请求的拦截器 * * @Component:该注解将其注入到IOC容器中 */@Slf4j@Componentpublic class RepeatSubmitInterceptor implements HandlerInterceptor { /** * Redis的API */ @Autowired private StringRedisTemplate stringRedisTemplate; /** * preHandler方法,在controller方法之前执行 * <p> * 判断条件仅仅是用了uri,实际开发中根据实际情况组合一个唯一识别的条件。 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { // 只拦截标注了@RepeatSubmit该注解 HandlerMethod method = (HandlerMethod) handler; // 标注在方法上的@RepeatSubmit RepeatSubmit repeatSubmitByMethod = AnnotationUtils.findAnnotation(method.getMethod(), RepeatSubmit.class); // 标注在controler类上的@RepeatSubmit RepeatSubmit repeatSubmitByCls = AnnotationUtils.findAnnotation(method.getMethod().getDeclaringClass(), RepeatSubmit.class); // 没有限制重复提交,直接跳过 if (Objects.isNull(repeatSubmitByMethod) && Objects.isNull(repeatSubmitByCls)) { log.info("isNull"); return true; } // todo: 组合判断条件,这里仅仅是演示,实际项目中根据架构组合条件 //请求的URI String uri = request.getRequestURI(); //存在即返回false,不存在即返回true Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(uri, "", Objects.nonNull(repeatSubmitByMethod) ? repeatSubmitByMethod.seconds() : repeatSubmitByCls.seconds(), TimeUnit.SECONDS); //如果存在,表示已经请求过了,直接抛出异常,由全局异常进行处理返回指定信息 if (ifAbsent != null && !ifAbsent) { String msg = String.format("url:[%s]重复请求", uri); log.warn(msg); // throw new RepeatSubmitException(msg); throw new Exception(msg); } } return true; }}配置拦截器package com.example.springboot_06.config;import com.example.springboot_06.intercept.RepeatSubmitInterceptor;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.WebMvcConfigurer;@Configurationpublic class WebConfig implements WebMvcConfigurer { @Autowired private RepeatSubmitInterceptor repeatSubmitInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { // 不拦截的uri final String[] commonExclude = {"/error", "/files/**"}; registry.addInterceptor(repeatSubmitInterceptor).excludePathPatterns(commonExclude); }}写个测试Controllerpackage com.example.springboot_06.controller;import com.example.springboot_06.intercept.RepeatSubmit;import lombok.extern.slf4j.Slf4j;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * 标注了@RepeatSubmit注解,全部的接口都需要拦截 * */@Slf4j@RestController@RequestMapping("/user")@RepeatSubmitpublic class UserController { @RequestMapping("/save") public ResponseEntity save() { log.info("/user/save"); return ResponseEntity.ok("save success"); }}测试

本文链接地址:https://www.jiuchutong.com/zhishi/310704.html 转载请保留说明!

上一篇:php判断数组元素不为空格的方法(php判断数据类型)

下一篇:织梦数据库类$dsql使用方法(安装织梦数据库连接不上)

  • 增值税发票综合服务平台验证口令失败
  • 退回的企业所得税怎么做账务处理
  • 税收滞纳金还会计算滞纳金吗
  • 耕地占用税是什么税种
  • 没有认证怎么办
  • 上月发票错误退回怎么做账
  • 无名称发票可以抵扣吗
  • 人身保险和意外保险是一个东西吗
  • 原材料作废品处理方法
  • 坏账的处理方法包括
  • 购买房产怎么确认收入
  • 专利技术转让使用费如何做会计处理?
  • 社保上面的每月的缴费基数是什么意思?
  • 销货清单怎么写才正规
  • 减少实收资本会引起资产和所有者权益发生变化吗
  • 收到增值税专用发票是已经付款了吗
  • 公司牌车还款从哪里扣款
  • 购买国税金税卡年费应该怎么做账务处理?
  • 模具维修费用清单表格
  • 发票上的税额和报税的数不一样,按照哪个报
  • 开增值税票需要合同吗
  • 融资租赁的租金包括
  • 实收资本印花税是一年一交吗
  • 纳税调整额怎么算出来的
  • 分支机构分配表 资产总额无法区分怎么办
  • 境内企业技术转让 增值税
  • 减免增值税可以税前扣除吗
  • 加计扣除两种情况
  • 对方开具红字发票过来怎么做进项税转出
  • 公司之间借款收据要领导签字吗
  • 汽车保险费里的钱能退吗
  • 发票开负数冲红做什么会计分录?
  • 工地买东西怎么记账
  • bios中英文对照表图新版
  • 东芝t351笔记本
  • 其他应收款计提坏账比例
  • 资产负债表中的预付款项目应根据什么填列
  • 预提费用冲销需要重新计提吗
  • PHP:xml_set_default_handler()的用法_XML解析器函数
  • 工厂返费能拿到吗
  • 正常运行英文
  • 没有抵扣的增值税怎么做账
  • win10专业版用户名和密码怎么取消
  • 对于接受捐赠的资产价值,应计入当期损益
  • 360se进程太多
  • 怎么检查当年的核酸结果
  • 付工程改造余款分录
  • 基于transformer的文本分类
  • 申报系统异常
  • php cat
  • css做三角
  • 中兴网管操作手册
  • user-interface console 0 指令无效
  • 决算清理期和库款报解整理期
  • 会计在账本上怎么记账
  • 进项税额转出需要补税
  • 分公司需要做纳税申报吗
  • celery eventlet
  • 应发工资账务处理
  • 外地预缴税款如何查询
  • 融资租赁业务如何开展
  • 包工包料工程预付款的支付比例
  • 投标保证金以现金形式转为履约保证金
  • Winserver2012下mysql 5.7解压版(zip)配置安装教程详解
  • 打印机向windows发送消息
  • win8系统安装步骤
  • centos安装类型选择
  • centos6.5mini安装教程
  • win7系统运行红警黑屏有声音
  • win8怎么调整屏幕分辨率
  • 深入理解rcu
  • 如何修改excel数据显示格式
  • 脚本控制三行三列怎么写
  • unity openvr
  • 重定向stdout
  • Android带有注册界面的简单app
  • 进口消费税怎么入账
  • 四个落实是哪四个落实
  • 10%加计抵减政策条件
  • 打单子的打印机能否打a4的纸
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设