一、什么是幂等。
1、什么是幂等:相同的条极下,执行多次结果拿到的结果都是一样的。举个例子比如相同的参数情况,执行多次,返回的数据都是样的。那什么情况下要考虑幂等,重复新增数据。
2、解决方案:解决的方式有很多种,本文使用的是本地锁。
二、实现思路
1、首先我们要确定多少时间内,相同请求参数视为一次请求,比如2秒内相同参数,无论请求多少次都视为一次请求。
2、一次请求的判断依据是什么,肯定是相同的形参,请求相同的接口,在1的时间范围内视为相同的请求。所以我们可以考虑通过参数生成一个唯一标识,这样我们根据唯一标识来判断。
三、代码实现
1、这里我选择spring的redis来实现,但如果有集群的情况,还是要用集群redis来处理。当第一次获取请求时,根据请求url、controller层调用的方法、请求参数生成MD5值这三个条件作为依据,将其作为redis的key和value值,并设置失效时间,当在失效时间之内再次请求时,根据是否已存在key值来判断接收还是拒绝请求来实现拦截。
2、pom.xml依赖
org.springframework.bootspring-boot-starter-data-redisio.lettucelettuce-core2.0.6.RELEASEorg.aspectjaspectjweaver1.8.9redis.clientsjedis2.9.1org.apache.commonscommons-pool22.6.0com.alibabafastjson1.2.31
3、在application.yml中配置redis
spring:
redis:
database: 0
host: XXX
port: 6379
password: XXX
timeout: 1000
pool:
max-active: 1
max-wait: 10
max-idle: 2
min-idle: 50
4、自定义异常类IdempotentException
package com.demo.controller;
public class IdempotentException extends RuntimeException {
public IdempotentException(String message) {
super(message);
}
@Override
public String getMessage() {
return super.getMessage();
}
}
5、自定义注解
package com.demo.controller;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Idempotent {
// redis的key值一部分
String value();
// 过期时间
long expireMillis();
}
6、自定义切面
package com.demo.controller;
import java.lang.reflect.Method;
import java.util.Objects;
import javax.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCommands;
@Component
@Aspect
@ConditionalOnClass(RedisTemplate.class)
public class IdempotentAspect {
private static final String KEY_TEMPLATE = "idempotent_%s";
@Resource
private RedisTemplate redisTemplate;
//填写扫描加了自定义注解的类所在的包。
@Pointcut("@annotation(com.demo.controller.Idempotent)")
public void executeIdempotent() {
}
@Around("executeIdempotent()") //环绕通知
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
Idempotent idempotent = method.getAnnotation(Idempotent.class);
//注意Key的生成规则
String key = String.format(KEY_TEMPLATE,
idempotent.value() + "_" + KeyUtil.generate(method, joinPoint.getArgs()));
String redisRes = redisTemplate
.execute((RedisCallback) conn -> ((JedisCommands) conn.getNativeConnection()).set(key, key,
"NX", "PX", idempotent.expireMillis()));
if (Objects.equals("OK", redisRes)) {
return joinPoint.proceed();
} else {
throw new IdempotentException("Idempotent hits, key=" + key);
}
}
}
//注意这里不需要释放锁操作,因为如果释放了,在限定时间内,请求还是会再进来,所以不能释放锁操作。
7、Key生成工具类
package com.demo.controller;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.alibaba.fastjson.JSON;
public class KeyUtil {
public static String generate(Method method, Object... args) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder(method.toString());
for (Object arg : args) {
sb.append(toString(arg));
}
return md5(sb.toString());
}
private static String toString(Object object) {
if (object == null) {
return "null";
}
if (object instanceof Number) {
return object.toString();
}
return JSON.toJSONString(object);
}
public static String md5(String str) {
StringBuilder buf = new StringBuilder();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte b[] = md.digest();
int i;
for (int offset = 0; offset
8、在Controller中标记注解
package com.demo.controller;
import javax.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@Resource
private RedisTemplate redisTemplate;
@PostMapping("/redis")
@Idempotent(value = "/redis", expireMillis = 5000L)
public String redis(@RequestBody User user) {
return "redis access ok:" + user.getUserName() + " " + user.getUserAge();
}
}
到此这篇关于Spring Boot通过Redis实现防止重复提交的文章就介绍到这了,更多相关SpringBoot Redis防止重复提交内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!
