AOP思想配置动态数据源

package com.nio.vrs.fota.aop;

import com.nio.common.db.DynamicDataSource;
import com.nio.vrs.fota.annotation.TargetDataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @description: 数据源切换切片
 * @create: 2019-03-12 15:22
 **/
@Aspect
@Order(value = 1)  //设置AOP的执行顺序在事务开启之前
@Component
public class DataSourceAspect {
    private Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    /**
     * 功能描述 : 切入点
     *
     * @return void
     * @Author pengpeng.wang.o
     * @Date 15:28 2019/3/12
     * @Param: []
     **/
    @Pointcut("execution(* com.nio.vrs.fota.service..*.*(..))")
    public void pointCut() {
    }

    /**
     * 功能描述 : 切换数据源
     *
     * @return void
     * @Author pengpeng.wang.o
     * @Date 15:38 2019/3/12
     * @Param: [joinPoint]
     **/
    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            Class<?> clazz = joinPoint.getTarget().getClass();
            method = clazz.getMethod(method.getName(), method.getParameterTypes());
            if (method != null && method.isAnnotationPresent(TargetDataSource.class)) {
                TargetDataSource dataSource = method.getAnnotation(TargetDataSource.class);
                String dataSourceName = dataSource.value().getName();
                DynamicDataSource.setDataSource(dataSourceName);
                logger.info("current thread " + Thread.currentThread().getName() + " add " + dataSourceName + " to ThreadLocal");
            } else {
                logger.info("switch datasource fail,use default");
            }
        } catch (NoSuchMethodException e) {
            logger.error("current thread " + Thread.currentThread().getName() + " add data to ThreadLocal error", e);
        }
    }

    @After("pointCut()")
    public void after(){
        DynamicDataSource.clearDataSource();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38987366/article/details/89332897
今日推荐