spring通过AbstractRouteDataSource 配置动态数据源

5 篇文章 0 订阅
1 篇文章 0 订阅

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

 

 

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

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

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值