引出
## 幂等
需要保存或更新时不能重复提交,可以在controller的方法上增加@XXIdempotent注解
这是一个使用Spring Boot实现的Java切面,名为IdempotentAspect,用于防止重复请求被处理。该切面使用@Around注解拦截使用**@XXIdempotent**注解的方法调用。然后,它基于方法名和其参数生成一个唯一的键。如果在缓存中找不到该键,则执行方法调用并将该键添加到缓存中。如果在缓存中找到该键,则不执行方法调用并返回一个失败消息。
具体是怎么来实现这个过程?
private static final TimedCache<String, String> TIMED_CACHE = CacheUtil.newTimedCache(1000L);
第一步、使用Hutool库的CacheUtil创建了一个定时缓存。对被缓存的对象定义一个过期时间,当对象超过过期时间会被清理。
第二步、generate方法用于通过连接方法名和其参数来创建唯一的键。将HttpServletRequest对象使用toString方法转换为字符串。然后,使用SecureUtil.md5方法对连接的字符串进行哈希处理。变成唯一的Key。
public static String generate(String methodName, Object[] args) {
Objects.requireNonNull(methodName, "methodName must not be null");
String argsString = (String)Arrays.stream(args).map((it) -> {
return it instanceof HttpServletRequest ? "HttpServletRequest" : it.toString();
}).collect(Collectors.joining(","));
StringJoiner joiner = new StringJoiner(":");
joiner.add(methodName).add(argsString);
LogUtil.debug("方法参数:{}", new Object[]{joiner.toString()});
return SecureUtil.md5(joiner.toString());
}
第三步、判断是否过期。
String s = (String)TIMED_CACHE.get(key);
if (s == null) {
TIMED_CACHE.put(key, "false");
return joinPoint.proceed();
} else {
LogUtil.info("拦截方法【{}】", new Object[]{method.getName()});
return Result.fail("你的操作太频繁了!");
}
该切面还支持在@XXIdempotent注解中使用SpEL表达式,以基于方法参数生成动态键。使用Spring Expression Language解析器评估SpEL表达式,并将结果用作键的一部分。
分布式的考虑
在单体的系统中,借助本地内存来锁请求是一种简单且高效的方法,而进入到分布式的环境下,这样的设计就不再可用了。在这类大型系统中,通常借用分布式redis来作为存储的介质,本质的原理是非常相似的。
import com.qianxian.common.exception.AppException;
import com.qianxian.common.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
/**
* 防重复提交
* @date 2023/5/31
* @return
*/
@Component
@Aspect
@Slf4j
public class PreventSubmitAspect {
/**
* 放重redis前缀
*/
private static String API_PREVENT_SUBMIT = "api:preventSubmit:";
/**
* 放重分布式锁前缀
*/
private static String API_LOCK_PREVENT_SUBMIT = "api:preventSubmit:lock:";
/**
* 失效时间
*/
private static Integer INVALID_NUMBER = 3;
/**
* redis
*/
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 分布式锁
*/
@Autowired
private RedissonClient redissonClient;
/**
* 防重
* @date 2020/8/12
* @return
*/
@Around("@annotation(com.qianxian.user.annotation.PreventSubmit)")
public Object preventSubmitAspect(ProceedingJoinPoint joinPoint) throws Throwable {
RLock lock = null;
try {
//获取目标方法的参数
Object[] args = joinPoint.getArgs();
//获取当前request请求
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
//获取请求地址
String requestUri = request.getRequestURI();
//获取用户ID
Long userId = null;
try {
userId = TokenUtil.getUserId(request);
}catch (Exception e){}
//拼接锁前缀,采用同一方法,同一用户,同一接口
String temp = requestUri.concat(Arrays.asList(args).toString()) + (userId != null ? userId : "");
temp = temp.replaceAll("/","");
//拼接rediskey
String lockPrefix = API_LOCK_PREVENT_SUBMIT.concat(temp);
String redisPrefix = API_PREVENT_SUBMIT.concat(temp);
/**
* 对同一方法同一用户同一参数加锁,即使获取不到用户ID,每个用户请求数据也会不一致,不会造成接口堵塞
*/
lock = this.redissonClient.getLock(lockPrefix);
lock.lock();
String flag = this.stringRedisTemplate.opsForValue().get(redisPrefix);
if(StringUtils.isNotEmpty(flag)){
throw new AppException("您当前的操作太频繁了,请稍后再试!");
}
//存入redis,设置失效时间
this.stringRedisTemplate.opsForValue()
.set(redisPrefix,redisPrefix,INVALID_NUMBER, TimeUnit.SECONDS);
//执行目标方法
Object result = joinPoint.proceed(args);
return result;
}finally {
if(lock != null){
lock.unlock();
}
}
}
}