SpringBoot學習---第五篇:動態資料來源(多資料來源自動切換)
阿新 • • 發佈:2019-01-27
目錄
一、應用場景
專案需要從自己的資料庫上讀取和管理資料外,還有一部分業務涉及到其他多個數據庫。
為了能夠靈活地指定具體的資料庫,本文基於註解和AOP的方法實現多資料來源自動切換。在使用過程中,只需要添加註解就可以使用,簡單方便。
二、準備工作
2.1 建立資料表
USE test; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `age` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 USE test1; CREATE TABLE `teacher` ( `tid` int(11) NOT NULL AUTO_INCREMENT, `tname` varchar(255) NOT NULL, `tage` int(11) NOT NULL, PRIMARY KEY (`tid`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 USE test2; CREATE TABLE `student` ( `sid` int(11) NOT NULL AUTO_INCREMENT, `sname` varchar(255) NOT NULL, `sage` int(11) NOT NULL, PRIMARY KEY (`sid`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
2.2 新增依賴
spring boot:1.5.8.RELEASE
mysql:5.1.44
mybatis:1.3.2
druid:1.1.3
<?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.example</groupId> <artifactId>dynamic-data-source</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>dynamic-data-source</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.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-web</artifactId> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!--aop--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!--資料庫連線池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- mybatis generator 自動生成程式碼外掛 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> </build> </project>
2.3 生成 bean、dao、mapper
三、動態資料來源
3.1 配置檔案 application.properties
custom.datasource.defaultname=default custom.datasource.names=ds1,ds2 # 預設資料來源 custom.datasource.driver-class-name=com.mysql.jdbc.Driver custom.datasource.url=jdbc:mysql://localhost:3306/test custom.datasource.username=root custom.datasource.password=root # 更多資料來源 custom.datasource.ds1.driver-class-name=com.mysql.jdbc.Driver custom.datasource.ds1.url=jdbc:mysql://localhost:3306/test1 custom.datasource.ds1.username=root custom.datasource.ds1.password=root custom.datasource.ds2.driver-class-name=com.mysql.jdbc.Driver custom.datasource.ds2.url=jdbc:mysql://localhost:3306/test2 custom.datasource.ds2.username=root custom.datasource.ds2.password=root custom.datasource.filters=stat custom.datasource.maxActive=100 custom.datasource.initialSize=1 custom.datasource.minIdle=1 custom.datasource.timeBetweenEvictionRunsMillis=60000 custom.datasource.minEvictableIdleTimeMillis=300000 custom.datasource.validationQuery=select 'x' custom.datasource.testWhileIdle=true custom.datasource.testOnBorrow=false custom.datasource.testOnReturn=false custom.datasource.poolPreparedStatements=true custom.datasource.maxOpenPreparedStatements=100 mybatis.type-aliases-package=com.example.demo.model.* mybatis.mapper-locations=classpath:mapper/**/*.xml
3.2 動態資料來源核心程式碼
DynamicDataSource:動態資料來源切換;
DynamicDataSourceAspect:利用AOP切面實現資料來源的動態切換;
DynamicDataSourceContextHolder:動態切換資料來源;
DynamicDataSourceRegister:動態資料來源註冊;
TargetDataSource:在方法上使用,用於指定使用哪個資料來源。
package com.example.demo.datasource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 動態資料來源
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}
package com.example.demo.datasource;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 切換資料來源Advice
*/
@Aspect
@Order(-1)// 保證該AOP在@Transactional之前執行
@Component
public class DynamicDataSourceAspect {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);
@Before("@annotation(ds)")
public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
String dsId = ds.name();
if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
logger.error("資料來源[{}]不存在,使用預設資料來源 > {}", ds.name(), point.getSignature());
}else {
logger.debug("Use DataSource : {} > {}", dsId, point.getSignature());
DynamicDataSourceContextHolder.setDataSourceType(dsId);
}
}
@After("@annotation(ds)")
public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
logger.debug("Revert DataSource : {} > {}", ds.name(), point.getSignature());
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
package com.example.demo.datasource;
import java.util.ArrayList;
import java.util.List;
public class DynamicDataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
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();
}
/**
* 判斷指定DataSrouce當前是否存在
*/
public static boolean containsDataSource(String dataSourceId){
return dataSourceIds.contains(dataSourceId);
}
}
package com.example.demo.datasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.bind.RelaxedDataBinder;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* 動態資料來源註冊
* 啟動動態資料來源請在啟動類中 新增 @Import(DynamicDataSourceRegister.class)
*/
public class DynamicDataSourceRegister
implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class);
private ConversionService conversionService = new DefaultConversionService();
private PropertyValues dataSourcePropertyValues;
// 如配置檔案中未指定資料來源型別,使用該預設值
private static final Object DATASOURCE_TYPE_DEFAULT = "com.alibaba.druid.pool.DruidDataSource";
// 資料來源
private DataSource defaultDataSource;
private Map<String, DataSource> customDataSources = new HashMap<>();
private static String DB_NAME = "names";
private static String DB_DEFAULT_VALUE = "custom.datasource"; //配置檔案中字首
@Value("${bi.datasource.defaultname}")
private String defaultDbname;
//載入多資料來源配置
@Override
public void setEnvironment(Environment env) {
initDefaultDataSource(env);
initCustomDataSources(env);
}
//初始化主資料來源
private void initDefaultDataSource(Environment env) {
// 讀取主資料來源
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, DB_DEFAULT_VALUE+".");
Map<String, Object> dsMap = new HashMap<>();
dsMap.put("type", propertyResolver.getProperty("type"));
dsMap.put("driver-class-name", propertyResolver.getProperty("driver-class-name"));
dsMap.put("url", propertyResolver.getProperty("url"));
dsMap.put("username", propertyResolver.getProperty("username"));
dsMap.put("password", propertyResolver.getProperty("password"));
defaultDataSource = buildDataSource(dsMap);
customDataSources.put(defaultDbname,defaultDataSource);//預設資料來源放到動態資料來源裡
dataBinder(defaultDataSource, env);
}
//為DataSource繫結更多資料
private void dataBinder(DataSource dataSource, Environment env) {
RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource);
//dataBinder.setValidator(new LocalValidatorFactory().run(this.applicationContext));
dataBinder.setConversionService(conversionService);
dataBinder.setIgnoreNestedProperties(false);//false
dataBinder.setIgnoreInvalidFields(false);//false
dataBinder.setIgnoreUnknownFields(true);//true
if (dataSourcePropertyValues == null) {
Map<String, Object> rpr = new RelaxedPropertyResolver(env, DB_DEFAULT_VALUE).getSubProperties(".");
Map<String, Object> values = new HashMap<String, Object>(rpr);
// 排除已經設定的屬性
values.remove("type");
values.remove("driver-class-name");
values.remove("url");
values.remove("username");
values.remove("password");
dataSourcePropertyValues = new MutablePropertyValues(values);
}
dataBinder.bind(dataSourcePropertyValues);
}
//初始化更多資料來源
private void initCustomDataSources(Environment env) {
// 讀取配置檔案獲取更多資料來源,也可以通過defaultDataSource讀取資料庫獲取更多資料來源
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env,DB_DEFAULT_VALUE+".");
String dsPrefixs = propertyResolver.getProperty(DB_NAME);
for (String dsPrefix : dsPrefixs.split(",")) {// 多個數據源
Map<String, Object> dsMap = propertyResolver.getSubProperties(dsPrefix + ".");
DataSource ds = buildDataSource(dsMap);
customDataSources.put(dsPrefix, ds);
dataBinder(ds, env);
}
}
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
// 將主資料來源新增到更多資料來源中
targetDataSources.put("dataSource", defaultDataSource);
DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
// 新增更多資料來源
targetDataSources.putAll(customDataSources);
for (String key : customDataSources.keySet()) {
DynamicDataSourceContextHolder.dataSourceIds.add(key);
}
// 建立DynamicDataSource
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(DynamicDataSource.class);
beanDefinition.setSynthetic(true);
MutablePropertyValues mpv = beanDefinition.getPropertyValues();
mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
mpv.addPropertyValue("targetDataSources", targetDataSources);
registry.registerBeanDefinition("dataSource", beanDefinition);
logger.info("Dynamic DataSource Registry");
}
//建立DataSource
@SuppressWarnings("unchecked")
public DataSource buildDataSource(Map<String, Object> dsMap) {
try {
Object type = dsMap.get("type");
if (type == null)
type = DATASOURCE_TYPE_DEFAULT;// 預設DataSource
Class<? extends DataSource> dataSourceType;
dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);
String driverClassName = dsMap.get("driver-class-name").toString();
String url = dsMap.get("url").toString();
String username = dsMap.get("username").toString();
String password = dsMap.get("password").toString();
DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url)
.username(username).password(password).type(dataSourceType);
return factory.build();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
package com.example.demo.datasource;
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;
// 在方法上使用,用於指定使用哪個資料來源
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
String name();
}
3.3 啟動類添加註解
添加註解 @Import :註冊動態多資料來源;
新增 @MapperScan :將專案中對應的mapper類的路徑加進來
package com.example.demo;
import com.example.demo.datasource.DynamicDataSourceRegister;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
@SpringBootApplication
@Import({DynamicDataSourceRegister.class}) // 註冊動態多資料來源
@MapperScan("com.example.demo.dao")//將專案中對應的mapper類的路徑加進來就可以了
public class DynamicDataSourceApplication {
public static void main(String[] args) {
SpringApplication.run(DynamicDataSourceApplication.class, args);
}
}
四、使用方法
4.1 Controller
package com.example.demo.controller;
import com.example.demo.model.Student;
import com.example.demo.model.Teacher;
import com.example.demo.model.User;
import com.example.demo.service.DynamicDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping(value = "/dds")
public class DynamicDataSourceController {
@Autowired
private DynamicDataSourceService service;
@RequestMapping(value = "/user/{id}")
public User getAllUserData(@PathVariable Integer id){
return service.getUserData(id);
}
@RequestMapping(value = "/teacher/{id}")
public Teacher getAllTeacherData(@PathVariable Integer id) {
return service.getTeacherData(id);
}
@RequestMapping(value = "/student/{id}")
public Student getAllStudentData(@PathVariable Integer id) {
return service.getStudentData(id);
}
}
4.2 Service
註解@TargetDataSource 不能直接在介面類Mapper上使用,所以在Service上使用。
package com.example.demo.service;
import com.example.demo.dao.StudentMapper;
import com.example.demo.dao.TeacherMapper;
import com.example.demo.dao.UserMapper;
import com.example.demo.datasource.TargetDataSource;
import com.example.demo.model.Student;
import com.example.demo.model.Teacher;
import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DynamicDataSourceService {
@Autowired
private UserMapper userMapper;
@Autowired
private TeacherMapper teacherMapper;
@Autowired
private StudentMapper studentMapper;
//不指定資料來源使用預設資料來源
public User getUserData(Integer id) {
return userMapper.selectByPrimaryKey(id);
}
//指定資料來源-ds1
@TargetDataSource(name="ds1")
public Teacher getTeacherData(Integer id) {
return teacherMapper.selectByPrimaryKey(id);
}
//指定資料來源-ds2
@TargetDataSource(name="ds2")
public Student getStudentData(Integer id) {
return studentMapper.selectByPrimaryKey(id);
}
}
五、測試
- localhost:8080//dds/user/1
- localhost:8080//dds/teacher/1
- localhost:8080//dds/student/1
六、Springboot2.0動態多資料來源切換
Springboot 1.x 到 Springboot 2.0配置變化有一點變化。主要是 RelaxedPropertyResolver不再可以Environment自動處理。
主要 是 DynamicDataSourceRegister 中有部分方法不一樣。其他方法都不需要修改。
package com.example.demo.datasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* 動態資料來源註冊<br/>
* 啟動動態資料來源請在啟動類中 新增 @Import(DynamicDataSourceRegister.class)
*/
public class DynamicDataSourceRegister
implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class);
// 如配置檔案中未指定資料來源型別,使用該預設值
private static final Object DATASOURCE_TYPE_DEFAULT = "com.alibaba.druid.pool.DruidDataSource";
// 資料來源
private DataSource defaultDataSource;
private Map<String, DataSource> customDataSources = new HashMap<>();
private static String DB_NAME = "names";
private static String DB_DEFAULT_VALUE = "custom.datasource";
@Value("${bi.datasource.defaultname}")
private String defaultDbname;
/**
* 載入多資料來源配置
*/
@Override
public void setEnvironment(Environment env) {
initDefaultDataSource(env);
initCustomDataSources(env);
}
/**
* 1.5.8 初始化主資料來源
*/
// private void initDefaultDataSource(Environment env) {
// // 讀取主資料來源
// RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, DB_DEFAULT_VALUE+".");
// Map<String, Object> dsMap = new HashMap<>();
// dsMap.put("type", propertyResolver.getProperty("type"));
// dsMap.put("driver-class-name", propertyResolver.getProperty("driver-class-name"));
// dsMap.put("url", propertyResolver.getProperty("url"));
// dsMap.put("username", propertyResolver.getProperty("username"));
// dsMap.put("password", propertyResolver.getProperty("password"));
//
// defaultDataSource = buildDataSource(dsMap);
// customDataSources.put(defaultDbname,defaultDataSource);//預設資料來源放到動態資料來源裡
// dataBinder(defaultDataSource, env);
// }
/**
* 2.0.4 初始化主資料來源
*/
private void initDefaultDataSource(Environment env) {
// 讀取主資料來源
Map<String, Object> dsMap = new HashMap<>();
dsMap.put("type", env.getProperty(DB_DEFAULT_VALUE + "." + "type"));
dsMap.put("driver-class-name", env.getProperty(DB_DEFAULT_VALUE + "." + "driver-class-name"));
dsMap.put("url", env.getProperty(DB_DEFAULT_VALUE + "." + "url"));
dsMap.put("username", env.getProperty(DB_DEFAULT_VALUE + "." + "username"));
dsMap.put("password", env.getProperty(DB_DEFAULT_VALUE + "." + "password"));
defaultDataSource = buildDataSource(dsMap);
// customDataSources.put(defaultDbname,defaultDataSource);//預設資料來源放到動態資料來源裡
// dataBinder(defaultDataSource, env);
}
/**
* 為DataSource繫結更多資料
*
*/
// private void dataBinder(DataSource dataSource, Environment env) {
// RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource);
// //dataBinder.setValidator(new LocalValidatorFactory().run(this.applicationContext));
// dataBinder.setConversionService(conversionService);
// dataBinder.setIgnoreNestedProperties(false);//false
// dataBinder.setIgnoreInvalidFields(false);//false
// dataBinder.setIgnoreUnknownFields(true);//true
// if (dataSourcePropertyValues == null) {
// Map<String, Object> rpr = new RelaxedPropertyResolver(env, DB_DEFAULT_VALUE).getSubProperties(".");
// Map<String, Object> values = new HashMap<String, Object>(rpr);
// // 排除已經設定的屬性
// values.remove("type");
// values.remove("driver-class-name");
// values.remove("url");
// values.remove("username");
// values.remove("password");
// dataSourcePropertyValues = new MutablePropertyValues(values);
// }
// dataBinder.bind(dataSourcePropertyValues);
// }
// 初始化更多資料來源
private void initCustomDataSources(Environment env) {
// 讀取配置檔案獲取更多資料來源,也可以通過defaultDataSource讀取資料庫獲取更多資料來源
// RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env,DB_DEFAULT_VALUE+".");
String dsPrefixs = env.getProperty(DB_DEFAULT_VALUE + "." + DB_NAME);
for (String dsPrefix : dsPrefixs.split(",")) {// 多個數據源
Map<String, Object> dsMap = new HashMap<>();
dsMap.put("type", env.getProperty(DB_DEFAULT_VALUE + "." + dsPrefix + ".type"));
dsMap.put("driver-class-name", env.getProperty(DB_DEFAULT_VALUE + "." + dsPrefix + ".driver-class-name"));
dsMap.put("url", env.getProperty(DB_DEFAULT_VALUE + "." + dsPrefix + ".url"));
dsMap.put("username", env.getProperty(DB_DEFAULT_VALUE + "." + dsPrefix + ".username"));
dsMap.put("password", env.getProperty(DB_DEFAULT_VALUE + "." + dsPrefix + ".password"));
DataSource ds = buildDataSource(dsMap);
customDataSources.put(dsPrefix, ds);
}
}
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
// 將主資料來源新增到更多資料來源中
targetDataSources.put("dataSource", defaultDataSource);
DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
// 新增更多資料來源
targetDataSources.putAll(customDataSources);
for (String key : customDataSources.keySet()) {
DynamicDataSourceContextHolder.dataSourceIds.add(key);
}
// 建立DynamicDataSource
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(DynamicDataSource.class);
beanDefinition.setSynthetic(true);
MutablePropertyValues mpv = beanDefinition.getPropertyValues();
mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
mpv.addPropertyValue("targetDataSources", targetDataSources);
registry.registerBeanDefinition("dataSource", beanDefinition);
logger.info("Dynamic DataSource Registry");
}
// 建立DataSource
@SuppressWarnings("unchecked")
public DataSource buildDataSource(Map<String, Object> dsMap) {
try {
Object type = dsMap.get("type");
if (type == null)
type = DATASOURCE_TYPE_DEFAULT;// 預設DataSource
Class<? extends DataSource> dataSourceType;
dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);
String driverClassName = dsMap.get("driver-class-name").toString();
String url = dsMap.get("url").toString();
String username = dsMap.get("username").toString();
String password = dsMap.get("password").toString();
DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url)
.username(username).password(password).type(dataSourceType);
return factory.build();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}