cy
2022-06-21 129904537f66509f97b285e7eb4f42b3dc349dd0
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
package cn.ksource.core.dsource;
 
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
 
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;
 
import cn.ksource.core.util.ConvertUtil;
import cn.ksource.core.util.StringUtil;
 
public class DataSourceAspect implements MethodBeforeAdvice,AfterReturningAdvice,ThrowsAdvice  {
    
    /**
     * 方法和使用数据源key的对应关系
     */
    private List<String> aspectMethodPrefixOrSuffer = new ArrayList<String>();
    
    private int slaveNum = 0;
    
    //事务执行方法执行之前被调用  
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {  
        System.out.println("切入点: " + target.getClass().getName() + "类中" + method.getName() + "方法");  
        String methodName = method.getName();
        for(String value : aspectMethodPrefixOrSuffer) {
            if(isMatch(methodName, value)) {
                System.out.println("切换到: master");  
                DataSourceSwitcher.setMaster();
                return;
            }
        }
        
        //随机选择slave
        String randomNum = StringUtil.randomNumber(6);
        int totalNum = 0;
        for(int i=0; i<randomNum.length(); i++) {
            char c = randomNum.charAt(i);
            int num = ConvertUtil.obj2Int(c);
            totalNum += num;
        }
        
        int num = totalNum%slaveNum;
        
        System.out.println("切换到: slave"+num);  
        DataSourceSwitcher.setSlave(num);  
    }
 
 
 
 
    private boolean isMatch(String methodName, String value) {
        return methodName.startsWith(value) || methodName.endsWith(value);
    }  
  
    
    
    
    //事务方法执行完之后被调用  
    public void afterReturning(Object arg0, Method method, Object[] args, Object target) throws Throwable {  
    }  
  
    // 抛出Exception之后被调用  
    public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {  
        DataSourceSwitcher.setSlave(0);  
        System.out.println("出现异常,切换到: slave");  
    }
 
    
    public List<String> getAspectMethodPrefixOrSuffer() {
        return aspectMethodPrefixOrSuffer;
    }
 
    public void setAspectMethodPrefixOrSuffer(
            List<String> aspectMethodPrefixOrSuffer) {
        this.aspectMethodPrefixOrSuffer = aspectMethodPrefixOrSuffer;
    }
 
 
 
 
    public int getSlaveNum() {
        return slaveNum;
    }
 
 
 
 
    public void setSlaveNum(int slaveNum) {
        this.slaveNum = slaveNum;
    }
 
    
    
}