All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hecloud.runtime.database.datasource.DataSourceAspect Maven / Gradle / Ivy

There is a newer version: 1.0.8
Show newest version
package com.hecloud.runtime.database.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 数据源切面
 *
 * @author LoveinBJ
 */
@Component
@Aspect
public class DataSourceAspect {
    private static Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    @Pointcut(value = "@annotation(DataSourceSwitch)")
    private void changeDS() {
    }

    @Around(value = "changeDS() ", argNames = "pjp")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();
        DataSourceSwitch annotation = method.getAnnotation(DataSourceSwitch.class);
        boolean selectedDataSource = false;
        try {
            if (null == annotation) {
                // 被切面的类的方法上没有数据源开关的注解值,直接执行被切面的类的方法并返回结果
                return pjp.proceed();
            }
            selectedDataSource = true;
            if (annotation.slave()) {
                // 切面方法上指定用从库数据源,则进行数据源的切换
                if (logger.isDebugEnabled()) {
                    logger.debug("Method {} use slave datasource", method.getName());
                }
                DynamicDataSource.useSlave();
            } else {
                // 如果不适用从库数据源,则直接使用主库的数据源
                if (logger.isDebugEnabled()) {
                    logger.debug("Method {} use master datasource", method.getName());
                }
                DynamicDataSource.useMaster();
            }
            return pjp.proceed();
        } catch (Throwable e) {
            logger.error("DataSource switch exception:", e);
            throw e;
        } finally {
            if (selectedDataSource) {
                DynamicDataSource.reset();
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy