欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring4+dbcp+mysql6.06使用注解实现动态切库(不支持跨库事务)

程序员文章站 2024-03-18 08:41:58
...

maven依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mutil.transaction</groupId>
    <artifactId>transaction</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>transaction</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

db.properties

spring.datasource.sakila.url=jdbc:mysql://localhost:3306/sakila?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=true
spring.datasource.sakila.username=root
spring.datasource.sakila.password=root
spring.datasource.sakila.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.sakila.initialSize=1
spring.datasource.sakila.maxIdle=2
spring.datasource.sakila.minIdle=1


spring.datasource.library.url=jdbc:mysql://localhost:3306/library?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=true
spring.datasource.library.username=root
spring.datasource.library.password=root
spring.datasource.library.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.library.initialSize=1
spring.datasource.library.maxIdle=2
spring.datasource.library.minIdle=1

spring.datasource.defalut.defaultDataSourceName=libraryDataSource

DBConfig2 :配置数据源、DataSourceTransactionManager、JdbcTemplate

package com.mutil.transaction.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**
 * Created by WuTing on 2017/12/5.
 */
@Configuration
@PropertySource("classpath:db.properties")
public class DBConfig2 {

    @Bean("libraryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.library")
    @Primary
    public DataSource libraryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean("sakilaDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.sakila")
    public DataSource sakilaDataSource() {

        return DataSourceBuilder.create().build();
    }

    @Bean("dataSource")
    public DynamicDataSource dataSource() {

        return new DynamicDataSource("libraryDataSource");
    }

    @Bean("jdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("dataSource") DynamicDataSource dataSource) {

        return new JdbcTemplate(dataSource);
    }

    @Bean("transactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

DynamicDataSource:继承了AbstractRoutingDataSource,设置多个数据源,将数据源交给Spring控制

package com.mutil.transaction.config;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.sql.DataSource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import com.atomikos.jdbc.AtomikosDataSourceBean;

/**
 * Created by WuTing on 2017/12/5.
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    public DynamicDataSource(String defaultDataSourceName) {
        Map<Object, Object> dataSourcs = SpringContextUtil.getBeans(DataSource.class, DynamicDataSource.class);
        List dataSourceIds = dataSourcs.keySet().stream().collect(Collectors.toList());
        DataSourceContextHolder.dataSourceIds.addAll(dataSourceIds);
        this.setTargetDataSources(dataSourcs);
        this.setDefaultTargetDataSource(dataSourcs.get(defaultDataSourceName));
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSourceType();
    }

}

为了使用注解方式进行动态切换数据源,需要定义一个DataSource注解,并且使用AOP方式进行数据源动态切换。DataSourceAspect 切面便是用于数据源切换。

DataSource注解:可作用于方法、class上, 用于class表明当前class的所有方法使用相同的数据源,用于方法上申明当前方法使用的数据源,当同时用于方法和class上时,用于方法上优先级较高。

package com.mutil.transaction.config;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by WuTing on 2017/12/5.
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface DataSource {
    String value();
}

DataSourceAspect:用于动态切换数据源.

package com.mutil.transaction.config;

import java.lang.reflect.Method;

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.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * Created by WuTing on 2017/12/5.
 */
@Component
@Aspect
@Order(1)
public class DataSourceAspect {
    private static final Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    @Before(value = "execution(* com.mutil.transaction.service.*.*(..))")
    public void before(JoinPoint point) {
        DataSource annotation = getDataSourceAnnotation(point);
        if (annotation != null) {
            DataSourceContextHolder.setDataSourceType(annotation.value());
            logger.debug("Set DataSource : {} > {}", annotation.value(), point.getSignature());
        }
    }

    @After(value = "execution(* com.mutil.transaction.service.*.*(..))")
    public void restoreDataSource(JoinPoint point) {

        DataSource annotation = getDataSourceAnnotation(point);
        if (annotation != null) {
            logger.debug("Revert DataSource : {} > {}", annotation.value(), point.getSignature());
        }
        DataSourceContextHolder.clearDataSourceType();
    }

    private DataSource getDataSourceAnnotation(JoinPoint point) {
        DataSource annotation = null;
        Class[] parameterTypes = ((MethodSignature)point.getSignature()).getMethod().getParameterTypes();
        String methodName = point.getSignature().getName();
        try {
            Method method = point.getTarget().getClass().getMethod(methodName, parameterTypes);
            if (method.isAnnotationPresent(DataSource.class)) {
                annotation = method.getAnnotation(DataSource.class);
            } else {
                annotation = point.getTarget().getClass().getAnnotation(DataSource.class);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        return annotation;
    }
}

DataSourceContextHolder:数据源切换实现类

package com.mutil.transaction.config;

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

/**
 * Created by WuTing on 2017/12/5.
 */
public class DataSourceContextHolder {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
    public static List<String> dataSourceIds = new ArrayList<>();

    public static void setDataSourceType(String dataSourceType) {
        contextHolder.set(dataSourceType);
    }

    public static String getDataSourceType() {
        return contextHolder.get();
    }

    public static void clearDataSourceType() {
        contextHolder.remove();
    }

    public static boolean containsDataSource(String dataSourceId) {
        return dataSourceIds.contains(dataSourceId);
    }
}

项目地址:https://github.com/wutingting1993/transaction/tree/Switch-DB-Automatic/