SpringBoot+Mybatisplus实现多数据源整合的实践SpringBoot 版本为1.5.10.RELEASE,Mybatis plus 版本为2.1.8。
第⼀步:填写配置信息:
spring:
aop:
proxy-target-class: true
auto: true
datasource:
druid:
# 数据库 1
db1:
url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
username: root
password: root
driver-class-name: sql.jdbc.Driver
initialSize: 5
minIdle: 5
maxActive: 20
# 数据库 2
db2:
url: jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
username: root
password: root
driver-class-name: sql.jdbc.Driver
initialSize: 5
minIdle: 5
maxActive: 20
第⼆步:数据源配置:
@Configuration
@MapperScan({"com.warm.system.mapper*"})
public class MybatisPlusConfig {
/**
* mybatis-plus分页插件<br>
* ⽂档:mp.baomidou<br>
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的⽀持
return paginationInterceptor;
}
/**
* mybatis-plus SQL执⾏效率插件【⽣产环境可以关闭】
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor();
}
@Bean(name = "db1")
@ConfigurationProperties(prefix = "spring.datasource.druid.db1" )
public DataSource db1 () {
ate().build();
}
@Bean(name = "db2")
@ConfigurationProperties(prefix = "spring.datasource.druid.db2" )
public DataSource db2 () {
ate().build();
}
/**
* 动态数据源配置
* @return
*/
@Bean
@Primary
public DataSource multipleDataSource (@Qualifier("db1") DataSource db1,
@Qualifier("db2") DataSource db2 ) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
Map< Object, Object > targetDataSources = new HashMap<>();
targetDataSources.put(Value(), db1 );
targetDataSources.put(Value(), db2);
dynamicDataSource.setTargetDataSources(targetDataSources);
dynamicDataSource.setDefaultTargetDataSource(db1);
return dynamicDataSource;
}
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(multipleDataSource(db1(),db2()));
//sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*/*l"));
MybatisConfiguration configuration = new MybatisConfiguration();
//configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(false);
sqlSessionFactory.setConfiguration(configuration);
sqlSessionFactory.setPlugins(new Interceptor[]{ //PerformanceInterceptor(),OptimisticLockerInterceptor()
paginationInterceptor() //添加分页功能
});
sqlSessionFactory.setGlobalConfig(globalConfiguration());
Object();
}
@Bean
public GlobalConfiguration globalConfiguration() {
GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());
conf.setLogicDeleteValue("-1");
conf.setLogicNotDeleteValue("1");
conf.setIdType(0);
conf.setMetaObjectHandler(new MyMetaObjectHandler());
conf.setDbColumnUnderline(true);
conf.setRefresh(true);
return conf;
}
springframework事务}
第三步:利⽤AOP进⾏数据源的动态切换:
@Component
@Aspect
@Order(-100) //这是为了保证AOP在事务注解之前⽣效,Order的值越⼩,优先级越⾼@Slf4j
public class DataSourceSwitchAspect {
@Pointcut("execution(* com.warm.system.service.db1..*.*(..))")
private void db1Aspect() {
}
@Pointcut("execution(* com.warm.system.service.db2..*.*(..))")
private void db2Aspect() {
}
@Before( "db1Aspect()" )
public void db1() {
log.info("切换到db1 数据源...");
DbContextHolder.setDbType(DBTypeEnum.db1);
}
@Before("db2Aspect()" )
public void db2 () {
log.info("切换到db2 数据源...");
DbContextHolder.setDbType(DBTypeEnum.db2);
}
}
public class DbContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal<>();
/**
* 设置数据源
* @param dbTypeEnum
*/
public static void setDbType(DBTypeEnum dbTypeEnum) {
contextHolder.Value());
}
/**
* 取得当前数据源
* @return
*/
public static String getDbType() {
return (String) ();
}
/
**
* 清除上下⽂数据
*/
public static void clearDbType() {
}
}
public enum DBTypeEnum {
db1("db1"), db2("db2");
private String value;
DBTypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public class DynamicDataSource extends AbstractRoutingDataSource {
/**
* 取得当前使⽤哪个数据源
* @return
*/
@Override
protected Object determineCurrentLookupKey() {
DbType();
}
}
OK!写个单元测试来验证⼀下:
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class DataTest {
@Autowired
private UserService userService;
@Autowired
private OrderService orderService;
@Test
public void test() {
}
如图所⽰,证明数据源能动态切换了。
具体项⽬结构和代码参考。
踩坑记录:
直接调⽤Mybatis plus 的service⽅法AOP不会⽣效,即数据源不会动态切换,解决⽅法:在⾃⼰的service层中封装⼀下,调⽤⾃定义的service⽅法AOP即能正常⽣效了,如下所⽰:@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public List<User> getUserList() {
return selectList(null);
}
}
#MyBatis
mybatis-plus:
mapper-locations: classpath:/mapper/*/*l
#实体扫描,多个package⽤逗号或者分号分隔
typeAliasesPackage: com.jinhuatuo.ity
global-config:
#主键类型 0:"数据库ID⾃增", 1:"⽤户输⼊ID",2:"全局唯⼀ID (数字类型唯⼀ID)", 3:"全局唯⼀ID UUID";
id-type: 0
#字段策略 0:"忽略判断",1:"⾮ NULL 判断"),2:"⾮空判断"
field-strategy: 2
#驼峰下划线转换
db-column-underline: true
#刷新mapper 调试神器
refresh-mapper: true
#数据库⼤写下划线转换
#capital-mode: true
#序列接⼝实现类配置
#key-generator: com.
#逻辑删除配置
#logic-delete-value: 0
#logic-not-delete-value: 1
#⾃定义填充策略接⼝实现
meta-object-handler: com.batis.MyMetaObjectHandler
#⾃定义SQL注⼊器
#sql-injector: com.
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
解决⽅法:所有这些配置在MybatisPlusConfig 类中⽤代码的⽅式进⾏配置,分页插件亦是如此,否则统计列表总数的数据会拿不到,参考代码即可。
在l配置
logging:
level: debug
控制台也不会打印Mybatis 执⾏的SQL语句,解决⽅法:⾃定义⽇志输出⽅案,如在classpath下直接引⼊⽇志配置⽂件如l即可,同时l⽆需再配置⽇志信息。logback-spring.x
ml配置参考:
<?xml version="1.0" encoding="UTF-8"?>
<!-- scan:配置⽂件如果发⽣改变,将会重新加载,默认值为true -->
<configuration scan="true" scanPeriod="10 seconds">
<!-- <include resource="org/springframework/boot/logging/l"/> -->
<!-- ⽇志⽂件路径 -->
<!-- <springProperty name="logFilePath" source="logging.path"/> -->
<property resource="l" />
<substitutionProperty name="LOG_HOME" value="${logging.path}" />
<substitutionProperty name="PROJECT_NAME" value="${spring.application.name}" />
<!--<substitutionProperty name="CUR_NODE" value="${de}" />-->
<!-- ⽇志数据库路径 -->
<!-- <springProperty name="logDbPath" source="url"/>
<springProperty name="logDbDriver" source="driver-class-name"/>
<springProperty name="logDbUser" source="username"/>
<springProperty name="logDbPwd" source="password"/> -->
<!-- 将⽇志⽂件 -->
<appender name="file" class="ch.olling.RollingFileAppender">
<append>true</append>
<encoder>
<pattern>
[ %-5level] [%date{yyyy-MM-dd HH:mm:ss}] %logger{96} [%line] - %msg%n
</pattern>
<charset>utf-8</charset>
</encoder>
<rollingPolicy class="ch.olling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/${PROJECT_NAME}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.olling.SizeAndTimeBasedFNATP">
<maxFileSize>50 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--最多保留30天log-->
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>
<!-- 将⽇志错误⽂件-->
<appender name="file_error" class="ch.olling.RollingFileAppender">
<append>true</append>
<encoder>
<pattern>
[ %-5level] [%date{yyyy-MM-dd HH:mm:ss}] %logger{96} [%line] - %msg%n
</pattern>
<charset>utf-8</charset>
</encoder>
<rollingPolicy class="ch.olling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/${PROJECT_NAME}-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.olling.SizeAndTimeBasedFNATP">
<maxFileSize>50 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--最多保留30天log-->
<maxHistory>30</maxHistory>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
<!-- <onMatch>ACCEPT</onMatch>
<onMismatch>DENY </onMismatch> -->
</filter>
</appender>
<!-- 将⽇志写⼊控制台 -->
<appender name="console" class="ch.ConsoleAppender">
<encoder>
<pattern>
[ %-5level] [%date{yyyy-MM-dd HH:mm:ss}] %logger{96} [%line] - %msg%n
</pattern>
<!--<charset>utf-8</charset>-->
</encoder>
</appender>
<!-- 将⽇志写⼊数据库 -->
<!-- <appender name="DB-CLASSIC-MYSQL-POOL" class="ch.qos.logback.classic.db.DBAppender">
<connectionSource class="ch.db.DataSourceConnectionSource">
<dataSource class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<driverClassName>${logDbDriver}</driverClassName>
<url>${logDbPath}</url>
<username>${logDbUser}</username>
<password>${logDbPwd}</password>
</dataSource>
</connectionSource>
</appender> -->
<!-- spring扩展,分环境配置log信息 -->
<springProfile name="dev">
<!-- <logger name="sand.dao" level="DEBUG"/> -->
<!-- <logger name="org.springframework.web" level="INFO"/> -->
<logger name="org.springboot.sample" level="TRACE" />
<logger name="org.springframework.cloud" level="INFO" />
<logger name="comflix" level="INFO"></logger>
<logger name="org.springframework.boot" level="INFO"></logger>
<logger name="org.springframework.web" level="INFO"/>
<logger name="jdbc.sqltiming" level="debug"/>
<logger name="com.ibatis" level="debug" />
<logger name="com.ibatismon.jdbc.SimpleDataSource" level="debug" />
<logger name="com.ibatismon.jdbc.ScriptRunner" level="debug" />
<logger name="com.ine.impl.SqlMapClientDelegate" level="debug" />
<logger name="java.sql.Connection" level="debug" />
<logger name="java.sql.Statement" level="debug" />
<logger name="java.sql.PreparedStatement" level="debug" />
<logger name="java.sql.ResultSet" level="debug" />
<logger name="com.warm" level="debug"/>
<root level="DEBUG">
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
<root level="ERROR">
<appender-ref ref="file_error" />
<!-- <appender-ref ref="DB-CLASSIC-MYSQL-POOL" /> -->
</root>
</springProfile>
<springProfile name="test">
<logger name="org.springboot.sample" level="TRACE" />
<logger name="org.springframework.cloud" level="INFO" />
<logger name="comflix" level="INFO"></logger>
<logger name="org.springframework.boot" level="INFO"></logger>
<logger name="org.springframework.web" level="INFO"/>
<logger name="jdbc.sqltiming" level="debug"/>
<logger name="com.ibatis" level="debug" />
<logger name="com.ibatismon.jdbc.SimpleDataSource" level="debug" />
<logger name="com.ibatismon.jdbc.ScriptRunner" level="debug" />
<logger name="com.ine.impl.SqlMapClientDelegate" level="debug" />
<logger name="java.sql.Connection" level="debug" />
<logger name="java.sql.Statement" level="debug" />
<logger name="java.sql.PreparedStatement" level="debug" />
<logger name="java.sql.ResultSet" level="debug" />
<logger name="com.warm" level="DEBUG"/>
<root level="DEBUG">
<!-- <appender-ref ref="console" /> -->
<appender-ref ref="file" />
</root>
<root level="ERROR">
<appender-ref ref="file_error" />
<!-- <appender-ref ref="DB-CLASSIC-MYSQL-POOL" /> -->
</root>
</springProfile>
<springProfile name="prod">
<logger name="org.springboot.sample" level="TRACE" />
<logger name="org.springframework.cloud" level="INFO" />
<logger name="comflix" level="INFO"></logger>
<logger name="org.springframework.boot" level="INFO"></logger>
<logger name="org.springframework.web" level="INFO"/>
<logger name="jdbc.sqltiming" level="debug"/>
<logger name="com.ibatis" level="debug" />
<logger name="com.ibatismon.jdbc.SimpleDataSource" level="debug" />
<logger name="com.ibatismon.jdbc.ScriptRunner" level="debug" />
<logger name="com.ine.impl.SqlMapClientDelegate" level="debug" />
<logger name="java.sql.Connection" level="debug" />
<logger name="java.sql.Statement" level="debug" />
<logger name="java.sql.PreparedStatement" level="debug" />
<logger name="java.sql.ResultSet" level="debug" />
<logger name="com.warm" level="info"/>
<root level="DEBUG">
<!-- <appender-ref ref="console" /> -->
<appender-ref ref="file" />
</root>
<root level="ERROR">
<appender-ref ref="file_error" />
<!-- <appender-ref ref="DB-CLASSIC-MYSQL-POOL" /> -->
</root>
</springProfile>
</configuration>
到此这篇关于SpringBoot+Mybatis plus实现多数据源整合的实践的⽂章就介绍到这了,更多相关SpringBoot+Mybatis plus多数据源内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论