当前位置 博文首页 > wsc的博客:spring通过AbstractRouteDataSource 配置动态数据源

    wsc的博客:spring通过AbstractRouteDataSource 配置动态数据源

    作者:[db:作者] 时间:2021-06-23 21:21

    1.通过Bean.xml配置

    ?

    数据库的配置文件 DynamicDataSource.properties

    User=root
    Password=root
    test.Url=jdbc:mysql://localhost:3306/test
    Driver=com.mysql.jdbc.Driver
    hotel.Url=jdbc:mysql://localhost:3306/hotel
    

    继承自AbstractRouteDataSource 的DynamicDataSource

    package com.wsc.DBMySQL;
    
    import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
    import org.springframework.stereotype.Component;
    
    /**
     * @Author: wsc
     * @Date: 2019/7/17 0:13
     */
    public class DynamicDataSource extends AbstractRoutingDataSource {
    	@Override
    	protected Object determineCurrentLookupKey() {
    		return CustomerContextHolder.getCustomerType();
    	}
    }
    

    数据共享的 CustomerContextHolder.java

    package com.wsc.DBMySQL;
    public class CustomerContextHolder {
        public static final String DATA_SOURCE_A = "test";
        public static final String DATA_SOURCE_B = "hotel ";
        private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
        public static void setCustomerType(String customerType) {
            contextHolder.set(customerType);
        }
        public static String getCustomerType() {
            return contextHolder.get();
        }
        public static void clearCustomerType() {
            contextHolder.remove();
        }
    }
    自定义的接口

    ?

    package com.wsc.AOP;
    
    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    import org.springframework.core.annotation.AliasFor;
    
    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    /**
     * 
     * @author dell
     *
     */
    public @interface CommDB {
    	 
    	String value() default "test";
    
    }
    
    
    
    

    对自定义的接口添加Aop进行方法增强

    package com.wsc.AOP;
    
    import javax.annotation.Resource;
    
    import com.wsc.DBMySQL.CustomerContextHolder;
    import com.wsc.DBMySQL.DynamicDataSource;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.stereotype.Component;
    
    @Aspect
    @Component
    public class CommDB_AOP {
    
    	 @Pointcut("@annotation(com.wsc.AOP.CommDB)")
    	 public void pointCut() {};
    
    	@Before(value="pointCut() && @annotation(db)",argNames ="db")
    	 public void before(JoinPoint joinPoint,CommDB db) {
    		 String dbName = db.value();
    		 CustomerContextHolder.setCustomerType(dbName);
    	 }
    	
    }
    

    执行的SQL测试语句

    package com.wsc.DBMySQL;
    
    import com.wsc.AOP.CommDB;
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.beans.factory.config.BeanPostProcessor;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Component;
    import org.springframework.stereotype.Service;
    
    /**
     * @author  wsc
     */
    @Service
    public class SQL_execute {
    
    	@Autowired
    	private JdbcTemplate jdbcTemplate;
    
    	@CommDB
    	public void insertData(){
    		String sql = "insert into img set belong=?,src=?";
    		jdbcTemplate.update(sql,new Object[] {"wsc","c:/img"});
    		
    	}
    	@CommDB("test")
    	public void insertData2(){
    		String sql = "insert into img set belong=?,src=?";
    		jdbcTemplate.update(sql,new Object[] {"wsc","c:/img"});
    
    	}
    
    	@CommDB("hotel")
    	public void insertData3(){
    		String sql = "insert into img set belong=?,src=?";
    		jdbcTemplate.update(sql,new Object[] {"wsc","c:/img"});
    
    	}
    
    }
    

    最关键的Bean.xml文件来了,我个人推荐使用IDEA编写Bean文件,因为我使用eclipse是DynamicDataSource的setTargetDataSources写错了eclipse尽然没报错也没变色,后来换成IDEA才找出这个错误,而且还有提示

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:context="http://www.springframework.org/schema/context"
            xmlns:aop="http://www.springframework.org/schema/aop"
            xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    
        <context:component-scan base-package="com.wsc"></context:component-scan>
    
        <context:component-scan base-package="com.wsc.DBMySQL" use-default-filters="false">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"></context:include-filter>
        </context:component-scan>
    
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    
        <context:property-placeholder location="classpath:DynamicDataSource.properties" />
    
        <bean id="parentDataSource" class="com.alibaba.druid.pool.DruidDataSource"
              destroy-method="close"  abstract="true" init-method="init" >
            <!-- 初始化连接大小 -->
            <property name="initialSize" value="2" />
            <!-- 连接池最大使用连接数量 -->
            <property name="maxActive" value="10" />
            <!-- 连接池最小空闲 -->
            <property name="minIdle" value="5" />
            <!-- 获取连接最大等待时间 -->
            <property name="maxWait" value="30000" />
            <!-- <property name="poolPreparedStatements" value="true" /> -->
            <!-- <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->
            <property name="validationQuery" value="SELECT 1" />
            <property name="testOnBorrow" value="false" />
            <property name="testOnReturn" value="false" />
            <property name="testWhileIdle" value="true" />
            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000" />
            <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            <property name="minEvictableIdleTimeMillis" value="25200000" />
            <!-- 打开removeAbandoned功能 -->
            <property name="removeAbandoned" value="true" />
            <!-- 1800秒,也就是30分钟 -->
            <property name="removeAbandonedTimeout" value="1800" />
            <!-- 关闭abanded连接时输出错误日志 -->
            <property name="logAbandoned" value="true" />
            <!-- 监控数据库 -->
            <!-- <property name="filters" value="stat" /> -->
            <property name="filters" value="mergeStat" />
        </bean>
    
        <bean id="dataSourceTest" parent="parentDataSource">
            <property name="username" value="${User}"></property>
            <property name="password" value="${Password}"></property>
            <property name="url" value="${test.Url}"></property>
            <property name="driverClassName" value="${Driver}"></property>
            <property name="maxActive" value="15"></property>
        </bean>
        <bean id="dataSourceHotel" parent="parentDataSource">
            <property name="username" value="${User}"></property>
            <property name="password" value="${Password}"></property>
            <property name="url" value="${hotel.Url}"></property>
            <property name="driverClassName" value="${Driver}"></property>
            <property name="maxActive" value="15"></property>
        </bean>
    
        <!--  据源配置 -->
        <bean id="DynamicDataSource" class="com.wsc.DBMySQL.DynamicDataSource">
            <property name="targetDataSources">
                <map key-type="java.lang.String">
                    <entry key="test" value-ref="dataSourceTest"></entry>
                    <entry key="hotel" value-ref="dataSourceHotel"></entry>
                </map>
            </property>
            <!--  注意了,下面是ref 而不是value ,很容易犯得错,ref才是映射 -->
            <property name="defaultTargetDataSource" ref="dataSourceHotel"></property>
        </bean>
    
        <bean id = "jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="DynamicDataSource"></property>
        </bean>
    
    
    
    </beans>

    执行测试文件,当然,我写在这里都是测试 通过的例子,你们可以参考参考

    import com.wsc.DBMySQL.SQL_execute;
    import org.junit.Test;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    /**
     * @Author: wsc
     * @Date: 2019/7/17 0:30
     */
    public class BeanXMLTest {
    
    
    	@Test
    	public void test1(){
    		ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("Bean.xml");
    		SQL_execute sql =(SQL_execute)context.getBean(SQL_execute.class);
    		sql.insertData();
    	}
    }
    

    2.通过SQLConfig.java注解的方式

    直接上代码,这里需要说明一下,由于方法是没有<bean>标签的parent属性,所以这里得全写上。

    package com.wsc.SQLConfig;
    
    import java.sql.SQLException;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.annotation.Resource;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.context.EmbeddedValueResolverAware;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.EnableAspectJAutoProxy;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.context.annotation.Scope;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.util.StringValueResolver;
    
    import com.alibaba.druid.pool.DruidDataSource;
    
    @ComponentScan("com.wsc")
    @Configuration
    @EnableAspectJAutoProxy
    public class SQLConfig{
    	
    	
    	@Bean(initMethod="init",destroyMethod="close")
    	public DruidDataSource dataSourceTest() throws SQLException{
    		DruidDataSource datasource = new DruidDataSource();
    		datasource.setInitialSize(2);
    		datasource.setMaxActive(10);
    		datasource.setMaxIdle(5);
    		datasource.setMaxWait(30000);
    		datasource.setValidationQuery("SELECT 1");
    		datasource.setTestOnBorrow(false);
    		datasource.setTestOnReturn(false);
    		datasource.setTestWhileIdle(true);
    		datasource.setTimeBetweenEvictionRunsMillis(60000);
    		datasource.setMinEvictableIdleTimeMillis(25200000);
    		datasource.setRemoveAbandoned(true);
    		datasource.setRemoveAbandonedTimeout(1800);
    		datasource.setLogAbandoned(true);
    		datasource.setFilters("mergeStat");
    		datasource.setUrl("jdbc:mysql://localhost:3306/test");
    		datasource.setUsername("root");
    		datasource.setPassword("root");
    		datasource.setDriverClassName("com.mysql.jdbc.Driver");
    		datasource.setMaxActive(15);
    		return datasource;
    		
    	}
    	
    	@Bean(initMethod="init",destroyMethod="close")
    	public DruidDataSource dataSourceHotel() throws SQLException {
    		DruidDataSource datasource = new DruidDataSource();
    		datasource.setInitialSize(2);
    		datasource.setMaxActive(10);
    		datasource.setMaxIdle(5);
    		datasource.setMaxWait(30000);
    		datasource.setValidationQuery("SELECT 1");
    		datasource.setTestOnBorrow(false);
    		datasource.setTestOnReturn(false);
    		datasource.setTestWhileIdle(true);
    		datasource.setTimeBetweenEvictionRunsMillis(60000);
    		datasource.setMinEvictableIdleTimeMillis(25200000);
    		datasource.setRemoveAbandoned(true);
    		datasource.setRemoveAbandonedTimeout(1800);
    		datasource.setLogAbandoned(true);
    		datasource.setFilters("mergeStat");
    		datasource.setUrl("jdbc:mysql://localhost:3306/hotel");
    		datasource.setUsername("root");
    		datasource.setPassword("root");
    		datasource.setDriverClassName("com.mysql.jdbc.Driver");
    		datasource.setMaxActive(15);
    		return datasource;
    	}
    	
    	@Bean
    	public DynamicDataSource dynamicDataSource() throws SQLException {
    		DynamicDataSource data = new DynamicDataSource();
    		DruidDataSource dataSourceTest = dataSourceTest();
    		DruidDataSource dataSourceHotel = dataSourceHotel();
    		System.out.println("test:\t"+dataSourceTest.getUrl());
    		System.out.println("hotel:\t"+dataSourceHotel.getUrl());
    		Map map = new HashMap();
    		map.put("test", dataSourceTest);
    		map.put("hotel", dataSourceHotel);
    		data.setTargetDataSources(map);
    		data.setDefaultTargetDataSource(dataSourceTest());
    		return data;
    	}
    	
    	@Bean
    	public JdbcTemplate jdbcTemplate() throws SQLException {
    		JdbcTemplate tem = new JdbcTemplate();
    		tem.setDataSource(dynamicDataSource());
    		return tem;
    	}
    }
    

    测试用例:

    import com.wsc.DBMySQL.SQL_execute;
    import org.junit.Test;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    /**
     * @Author: wsc
     * @Date: 2019/7/17 0:30
     */
    public class BeanXMLTest {
    
    
    	@Test
    	public void test1(){
    		ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("Bean.xml");
    		SQL_execute sql =(SQL_execute)context.getBean(SQL_execute.class);
    		sql.insertData();
    	}
    }
    

    ?

    ?

    如果喜欢的我的内容,就关注我一波吧!

    学习啊,学习啊,学习也是一种挣扎.