本文主要是介绍springboot+mybatis如何配多数据源,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
下面的案例:这是注解式的同一类型数据库的多数据源配置,将@DataChoose(value="mysql1")添加到要进行数据源切换的方法上,即可根据直接内设置的值进行数据源切换
如果你刚好需要,复制将配置改成你的就可以用,但是如果不想用注解式的,想其他方式的,
比如:根据方法名前缀切换、对指定包路径的类方法进行指定数据源切换,都可以,那就不要注解类,且把切面Aspect里的拦截设置改成你想要的拦截方式
配置文件:application.properties,因为是同种数据库,所以除了以下四个属性设置,要各自设置,其他的设置基本一份就可以
spring.mysql1.datasource.jdbc-url=jdbc:mysql://localhost:3306/testData1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8&allowPublicKeyRetrieval=true
spring.mysql1.datasource.username=root
spring.mysql1.datasource.password=666666
spring.mysql1.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.mysql2.datasource.jdbc-url=jdbc:mysql://localhost:3306/testData2?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8&allowPublicKeyRetrieval=true
spring.mysql2.datasource.username=root
spring.mysql2.datasource.password=666666
spring.mysql2.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
配置多个数据源实例:DataSourceConfig.java
package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;/*** @Author: lhs* @Description:* @Date: 2021/8/28 08:57* @Modified By:* @since v1.0.1*/
@Configuration
public class DataSourceConfig {@Bean(name = "mysql1")@ConfigurationProperties(prefix = "spring.datasource.mysql1")public DataSource dataSource1() {return DataSourceBuilder.create().build();}@Bean(name = "mysql2")@ConfigurationProperties(prefix = "spring.datasource.mysql2")public DataSource dataSource2() {return DataSourceBuilder.create().build();}/*** 动态数据源: 通过AOP在不同数据源之间动态切换** @return*/@Primary@Bean(name = "dynamicDS1")public DataSource dataSource() {DynamicDataSource dynamicDataSource = new DynamicDataSource();// 默认数据源dynamicDataSource.setDefaultTargetDataSource(dataSource1());// 配置多数据源Map<Object, Object> dsMap = new HashMap(5);dsMap.put(DataSourceEnum.MYSQL1, dataSource1());dsMap.put(DataSourceEnum.MYSQL2, dataSource2());dynamicDataSource.setTargetDataSources(dsMap);return dynamicDataSource;}/*** 配置@Transactional注解事物* @return*/@Beanpublic PlatformTransactionManager transactionManager() {return new DataSourceTransactionManager(dataSource());}}
数据源管理:DataSourceContextHolder.java
package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;/*** @Author: lhs* @Description:* @Date: 2021/8/28 08:57* @Modified By:* @since v1.0.1*/
public class DataSourceContextHolder {/*** 默认数据源*/public static final String DEFAULT_DS = "mysql1";private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();// 设置数据源名public static void setDB(String dbType) {contextHolder.set(dbType);}// 获取数据源名public static String getDB() {return (contextHolder.get());}// 清除数据源名public static void clearDB() {contextHolder.remove();}}
DataSourceEnum.java: 这个随意,怎样舒服怎样写,不一样非要照抄
package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;/*** @Author: lhs* @Description:* @Date: 2021/8/28 08:57* @Modified By:* @since v1.0.1*/
public enum DataSourceEnum {MYSQL("mysql1"), MYSQL("mysql2");private String value;DataSourceEnum(String value) {this.value = value;}public String getValue() {return this.value;}
}
DynamicDataSource.java
package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;/*** @Author: lhs* @Description:* @Date: 2021/8/28 08:57* @Modified By:* @since v1.0.1*/
public class DynamicDataSource extends AbstractRoutingDataSource {@Overrideprotected Object determineCurrentLookupKey() {return DataSourceContextHolder.getDB();}
}
DynamicDataSourceAspect.java: 设置切面拦截点,可根据自己的情况设置,此处设置的是对所有带此注解的方法根据注解的值进行数据源切换
package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;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.springframework.stereotype.Component;import java.lang.reflect.Method;/*** @Author: lhs* @Description:* @Date: 2021/8/27 23:02* @Modified By:* @since v1.0.1*/
@Aspect
@Component
public class DynamicDataSourceAspect {@Before("@annotation(DataChoose)")public void beforeSwitchDS(JoinPoint point){//获得当前访问的classClass<?> className = point.getTarget().getClass();//获得访问的方法名String methodName = point.getSignature().getName();//得到方法的参数的类型Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();String dataSource = DataSourceContextHolder.DEFAULT_DS;try {// 得到访问的方法对象Method method = className.getMethod(methodName, argClass);// 判断是否存在@DataChooseif (method.isAnnotationPresent(DataChoose.class)) {DataChoose annotation = method.getAnnotation(DataChoose.class);// 取出注解中的数据源名dataSource = annotation.value();}} catch (Exception e) {e.printStackTrace();}// 切换数据源DataSourceContextHolder.setDB(dataSource);}@After("@annotation(DataChoose)")public void afterSwitchDS(JoinPoint point){DataSourceContextHolder.clearDB();}
}
DataChoose.java 此为注解类
package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** @Author: lhs* @Description:* @Date: 2021/8/27 23:04* @Modified By:* @since v1.0.1*/@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD
})
public @interface DataChoose {String value() default "mysql1";
}
这篇关于springboot+mybatis如何配多数据源的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!