spring AOP配置读写分离

maven依赖引入


         aspectj
         aspectjrt
         1.5.3


         org.aspectj
         aspectjweaver
         1.8.9

srping配置文件引入aop



spring配置文件添加



      
      
          
          
      




      
      

          
              query*
              use*
              get*
              count*
              find*
              list*
              search*
          

      
      
      
          
              save*
              add*
              create*
              insert*
              update*
              merge*
              del*
              remove*
              put*
              write*
          
      


ReadWriteInterceptor.java

package com.keegoo.interceptor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.PatternMatchUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangshuang on 17/2/23.
 */
public class ReadWriteInterceptor {

    private static final String DB_SERVICE = "dbService";
    private List readMethodList = new ArrayList();
    private List writeMethodList = new ArrayList();

    public Object readOrWriteDB(ProceedingJoinPoint pjp) throws Throwable {
        String methodName = pjp.getSignature().getName();
        if (isChooseReadDB(methodName)) {
            //选择slave数据源
            System.out.print("==========================read");
        } else if (isChooseWriteDB(methodName)) {
            //选择master数据源
            System.out.print("==========================write");
        } else {
            //选择master数据源
            System.out.print("==========================else");
        }
        return pjp.proceed();
    }

    private boolean isChooseWriteDB(String methodName) {
        for (String mappedName : this.writeMethodList) {
            if (isMatch(methodName, mappedName)) {
                return true;
            }
        }
        return false;
    }

    private boolean isChooseReadDB(String methodName) {
        for (String mappedName : this.readMethodList) {
            if (isMatch(methodName, mappedName)) {
                return true;
            }
        }
        return false;
    }

    private boolean isMatch(String methodName, String mappedName) {
        return PatternMatchUtils.simpleMatch(mappedName, methodName);
    }

    public List getReadMethodList() {
        return readMethodList;
    }

    public void setReadMethodList(List readMethodList) {
        this.readMethodList = readMethodList;
    }

    public List getWriteMethodList() {
        return writeMethodList;
    }

    public void setWriteMethodList(List writeMethodList) {
        this.writeMethodList = writeMethodList;
    }

}


打印结果:

spring AOP配置读写分离_第1张图片
Paste_Image.png

你可能感兴趣的:(spring AOP配置读写分离)