yujian
2019-11-06 bef0ef19d792a16a31a59ec7beafc7b0885529fa
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package com.yeshi.fanli.aspect;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
 
import javax.annotation.Resource;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.yeshi.utils.JsonUtil;
 
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.annotation.RequestSerializableByKey;
 
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
 
@Component
@Aspect
@Order(4)
public class RequestSerializableAspect {
    @Resource
    private JedisPool jedisPool;
 
    private ExpressionParser parser = new SpelExpressionParser();
 
    private DefaultParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();
 
    /**
     * 获取表达的值
     * 
     * @param spELString
     * @param joinPoint
     * @return
     */
    public String generateKeyBySpEL(String spELString, ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] paramNames = nameDiscoverer.getParameterNames(methodSignature.getMethod());
        Expression expression = parser.parseExpression(spELString);
        EvaluationContext context = new StandardEvaluationContext();
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            context.setVariable(paramNames[i], args[i]);
        }
        return expression.getValue(context).toString();
    }
 
    @Around("execution(public * com.yeshi.fanli.controller.client.*.*.*(..))")
    public Object requestSerializable(ProceedingJoinPoint joinPoint) throws IOException {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        String cacheKey = null;
        try {
            Method realMethod = joinPoint.getTarget().getClass().getDeclaredMethod(joinPoint.getSignature().getName(),
                    targetMethod.getParameterTypes());
            Object[] args = joinPoint.getArgs();
            PrintWriter out = null;
            String[] strings = methodSignature.getParameterNames();
            Map<String, ParamsTypeValue> map = new HashMap<>();
            Class<?>[] types = methodSignature.getParameterTypes();
            for (int i = 0; i < strings.length; i++) {
                map.put(strings[i], new ParamsTypeValue(types[i], args[i]));
                if (args[i] instanceof PrintWriter) {
                    out = (PrintWriter) args[i];
                }
            }
 
            if (realMethod.isAnnotationPresent(RequestSerializableByKey.class)) {
                RequestSerializableByKey rs = realMethod.getAnnotation(RequestSerializableByKey.class);
 
                String key = rs.key();
                cacheKey = generateKeyBySpEL(key, joinPoint);
 
                try {// redis做原子性保护
                    if (!StringUtil.isNullOrEmpty(cacheKey)) {
                        cacheKey = joinPoint.getTarget().getClass().getName() + "." + targetMethod.getName() + "-"
                                + cacheKey;
                        String cacheAlias = cacheKey;
                        cacheKey = "rs-" + StringUtil.Md5(cacheKey);
                        // jiedis原子性做拦截
                        Jedis jedis = jedisPool.getResource();
                        long threadId= Thread.currentThread().getId();
                        LogHelper.test("进入拦截:"+cacheKey+"-"+threadId);
                        try {
                            Constant.waitingThreadSet.add(threadId);
                            long result = 0;
                            long startTime = System.currentTimeMillis();
                            // 等待响应
                            while (result <= 0) {
                                result = jedis.setnx(cacheKey, "1");
                                LogHelper.error("触发并发锁:" + cacheAlias);
                                LogHelper.error("redis键:" + cacheKey);
                                if (result <= 0) {
                                    LogHelper.test("等待:"+threadId);
                                    try {
                                        Thread.sleep(50);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    if (System.currentTimeMillis() - startTime > 1000 * 30L) {
                                        Constant.waitingThreadSet.remove(Thread.currentThread().getId());
                                        out.print(JsonUtil.loadFalseResult("连接超时"));
                                        return null;
                                    }
                                } else {
                                    // 设置30秒处理时间
                                    jedis.expire(cacheKey, 30);
                                    LogHelper.test("获取到锁:"+threadId);
                                    break;
                                }
                            }
 
                            if (result > 0) {
                                try {
                                    return joinPoint.proceed();
                                } catch (Throwable e) {
                                    e.printStackTrace();
                                    LogHelper.errorDetailInfo(e);
                                } finally {
                                    LogHelper.test("方法执行完毕:"+threadId);
                                    jedis.del(cacheKey);
                                    Constant.waitingThreadSet.remove(Thread.currentThread().getId());
                                    LogHelper.test("释放锁:"+threadId);
                                }
                            }
                        } finally {
                            jedisPool.returnResource(jedis);
                        }
                    }
                } catch (Exception e) {// 原子性保护出错
                    try {
                        return joinPoint.proceed();
                    } catch (Throwable e1) {
                        e.printStackTrace();
                        LogHelper.errorDetailInfo(e1);
                    }
                }
            }
 
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
 
        try {
            return joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
        } finally {
        }
        return null;
    }
 
    // 测试代码
    public void test() {
 
    }
 
    class ParamsTypeValue {
        Class<?> type;
        Object value;
 
        public ParamsTypeValue(Class<?> type, Object value) {
            this.type = type;
            this.value = value;
        }
 
        public ParamsTypeValue() {
 
        }
    }
 
}