liusheng
2023-11-17 054cfdd53b732d2f60627fc9ac7cf92233d3c200
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.ruoyi.common.config;
 
import com.ruoyi.common.annotation.NotRepeatCommit;
import com.ruoyi.common.filter.RepeatedlyRequestWrapper;
import com.ruoyi.common.utils.http.HttpHelper;
import org.apache.logging.log4j.util.Strings;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
 
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
 
@Aspect
@Component
public class IsAspectAspect {
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Around("@annotation(notRepeat)")
    public Object before(ProceedingJoinPoint point, NotRepeatCommit notRepeat) {
        String nowParams = "";
 
        String key = getKey(notRepeat.key(), point.getArgs());
        if (Strings.isNotBlank(key)) {
            // 不存在 就添加  缓存 设置 时间
            if (!redisTemplate.opsForValue().setIfAbsent(key, "1", notRepeat.value(), TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("请勿重复提交");
            }
        }
 
        try {
            return point.proceed();
        } catch (Throwable throwable) {
            throw new RuntimeException("服务器异常");
        }
    }
 
    /**
     * key 生成策略
     *
     * @param key  key表达式
     * @param args 参数
     * @return 生成的key
     */
    private String getKey(String key, Object[] args) {
        for (int i = 0; i < args.length; i++) {
            key = key.replace("arg[" + i + "]", args[i].toString());
        }
        return key;
    }
}