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();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值