1. Add maven dependencies
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.3</version> </dependency> <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>Copy the code
2. Configure application.yml
Database access configuration
# primary data source, default
druid:
datasource:
type: com. Alibaba. Druid. Pool. DruidDataSource driver - class - name: com. Mysql.. JDBC driver url: JDBC: mysql: / / 192.168.1.113:3306 /test? useUnicode=true&characterEncoding=utf-8
username: root
password: root
The following supplementary Settings for connection pooling apply to all of the above data sources
# initialize size, min, Max
initialSize: 5
minIdle: 5
maxActive: 20
Set the connection wait timeout
maxWait: 60000
Configure how often to detect idle connections that need to be closed, in milliseconds
timeBetweenEvictionRunsMillis: 60000
Set the minimum time for a connection to live in the pool in milliseconds
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
Turn on PSCache and specify the size of PSCache on each connection
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# Configure the filters for monitoring statistics interception. After removing the filters, the MONITORING interface SQL cannot be counted. 'wall' is used for the firewall
filters: stat,wall,log4j
Enable mergeSql via connectProperties; Slow SQL record
connectionProperties:
druid:
stat:
mergeSql: true
slowSqlMillis: 5000
# DruidDataSource datasource
# Multiple data sourcesmysql-db: datasource: names: logic,dao logic: driver-class-name: com.mysql.jdbc.Driver url: JDBC: mysql: / / 192.168.1.113:3306 /test1? useUnicode=true&characterEncoding=utf-8 username: root password: root dao: driver-class-name: com.mysql.jdbc.Driver url: JDBC: mysql: / / 192.168.1.113:3306 /test2? useUnicode=true&characterEncoding=utf-8
username: root
password: rootCopy the code
3. Configure dynamic data sources
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; Dynamic data source / * * * * @ author Chen Ziping * @ date 2017/10/9. * / public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected ObjectdetermineCurrentLookupKey() {
returnDataSourceHolder.getDataSource(); }}Copy the code
4. Configure the data source operation Holder
import java.util.ArrayList; import java.util.List; */ public class DataSourceHolder {// Thread local environment private static final ThreadLocal<String> contextHolders = new ThreadLocal<String>(); Public static List<String> dataSourceIds = new ArrayList<>(); // Set the data source public static voidsetDataSource(String customerType) { contextHolders.set(customerType); } // Get data source public static StringgetDataSource() {
return(String) contextHolders.get(); } // Clear the data source public static voidclearDataSource() { contextHolders.remove(); } /** * Check whether the specified DataSrouce exists * @param dataSourceId * @return
* @author SHANHY
* @create 2016年1月24日
*/
public static boolean containsDataSource(String dataSourceId){
returndataSourceIds.contains(dataSourceId); }}Copy the code
5. Read from the defined data source and configure it
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValues; 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.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; /** * Data source Configuration * @author * @date 2017/10/9. */ @component @configuration public class DynamicDataSourceConfig implements EnvironmentAware { private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceConfig.class); // defaultDataSource private DataSource defaultDataSource; // Private PropertyValues dataSourcePropertyValues; If the data source type is not specified in the configuration file, the default value is private static final Object DATASOURCE_TYPE_DEFAULT ="org.apache.tomcat.jdbc.pool.DataSource";
private ConversionService conversionService = new DefaultConversionService();
private Map<String, DataSource> customDataSources = new HashMap<>();
@Override
public void setEnvironment(Environment environment) {
initDefaultDatasource(environment);
initOtherDatasource(environment);
}
private void initOtherDatasource(Environment environment) {
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(environment, "mysql-db.datasource.");
String dsPrefixs = propertyResolver.getProperty("names");
for (String dsPrefix : dsPrefixs.split(",")) {/ / multiple data sources Map < String, Object > dsMap = propertyResolver. GetSubProperties (dsPrefix +"."); DataSource ds = buildDataSource(dsMap); customDataSources.put(dsPrefix, ds); dataBinder(ds, environment); }} private void initDefaultDatasource(Environment Environment) {// Read primary datasource RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(environment,"druid.datasource.");
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);
DataSourceHolder.dataSourceIds.add("ds1"); dataBinder(defaultDataSource, environment); } /** * create DataSource * @param dsMap * @return* @author SHANHY * @create January 24, 2016 */ @SuppressWarnings("unchecked")
public DataSource buildDataSource(Map<String, Object> dsMap) {
try {
Object type = dsMap.get("type");
if (type == null)
type= DATASOURCE_TYPE_DEFAULT; // 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();
}
returnnull; } @param DataSource * @param env * @author SHANHY * @create January 25, 2016 */ 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, "druid.datasource.").getSubProperties("."); Map<String, Object> values = new HashMap<>(rpr); // Remove values. Remove ("type");
values.remove("driver-class-name");
values.remove("url");
values.remove("username");
values.remove("password");
dataSourcePropertyValues = new MutablePropertyValues(values);
}
dataBinder.bind(dataSourcePropertyValues);
}
@Bean(name = "dataSource")
public DynamicDataSource dataSource() { DynamicDataSource dynamicDataSource = new DynamicDataSource(); . / / the default data source dynamicDataSource setDefaultTargetDataSource (defaultDataSource); DsMap <Object, Object> dsMap = new HashMap(5); dsMap.put("ds1", defaultDataSource);
dsMap.putAll(customDataSources);
for (String key : customDataSources.keySet())
DataSourceHolder.dataSourceIds.add(key);
dynamicDataSource.setTargetDataSources(dsMap);
returndynamicDataSource; }}Copy the code
6, dynamic switch key — AOP switch
*/ @retention (retentionPolicy.runtime) @target ({elementtype.method}) public @interface DS { String name() default"ds1";
}Copy the code
import com.chen.config.dynamicDS.DataSourceHolder; 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; /** * Set the data source Aspect * @author * @date 2017/10/9. */ @aspect @order (-1)// Ensure that this AOP implements @Component public class before @Transactional DynamicDataSourceAspect { private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class); @Before("@annotation(ds)")
public void changeDataSource(JoinPoint point, DS ds) throws Throwable {
String dsId = ds.name();
if(! DataSourceHolder.containsDataSource(dsId)) { logger.error("Data source [{}] does not exist, use default data source > {}", ds.name(), point.getSignature());
} else {
logger.debug("Use DataSource : {} > {}", ds.name(), point.getSignature());
DataSourceHolder.setDataSource(ds.name());
}
}
@After("@annotation(ds)")
public void restoreDataSource(JoinPoint point, DS ds) {
logger.debug("Revert DataSource : {} > {}", ds.name(), point.getSignature()); DataSourceHolder.clearDataSource(); }}Copy the code
1). Configure mapper
/** * @author * @date 2017/10/9. */ public interface DynamicDSMapper {Integer queryJournal(); String queryUser(); String queryType(); }Copy the code
<? xml version="1.0" encoding="UTF-8"? > <! DOCTYPE mapper PUBLIC"- / / mybatis.org//DTD Mapper / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chen.mapper.DynamicDSMapper">
<select id="queryJournal" resultType="java.lang.Integer">
SELECT uid FROM journal
</select>
<select id="queryUser" resultType="java.lang.String">
SELECT name FROM user
</select>
<select id="queryType" resultType="java.lang.String">
SELECT parent FROM p_type
</select>
</mapper>Copy the code
2) Configure service
/** * @author * @date 2017/10/9. */ @service public implements DynamicServciceImpl { @Autowired private DynamicDSMapper dynamicDSMapper; @DS() public Integerds1() {
return dynamicDSMapper.queryJournal();
}
@DS(name = "logic")
public String ds2() {
return dynamicDSMapper.queryUser();
}
@DS(name = "dao")
public String ds3() {
returndynamicDSMapper.queryType(); }}Copy the code
3) Unit test call
*/ @runwith (springrunner.class) @SpringbooTtest Public class TestDynamicDS { private Logger logger = LoggerFactory.getLogger(TestDynamicDS.class); // @Autowired private DynamicServcice dynamicServcice; @Test public voidtest() {
// Integer integer = dynamicServcice.ds1();
// logger.info("integer:"+integer);
// String ds2 = dynamicServcice.ds2();
// logger.info("ds2:"+ds2);
String ds3 = dynamicServcice.ds3();
logger.info("ds3:"+ds3); }}Copy the code
4) Test results