JAVA语言之Spring Boot + Mybatis多数据源和动态数据源配置方法[Java代码]
龚超 2018-07-20 来源 : 阅读 1074 评论 0

摘要:本文主要向大家介绍了JAVA语言的Spring Boot + Mybatis多数据源和动态数据源配置方法,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。

本文主要向大家介绍了JAVA语言的Spring Boot + Mybatis多数据源和动态数据源配置方法,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。

网上的文章基本上都是只有多数据源或只有动态数据源,而最近的项目需要同时使用两种方式,记录一下配置方法供大家参考。

应用场景

项目需要同时连接两个不同的数据库A, B,并且它们都为主从架构,一台写库,多台读库。

多数据源

首先要将spring boot自带的DataSourceAutoConfiguration禁掉,因为它会读取application.properties文件的spring.datasource.*属性并自动配置单数据源。在@SpringBootApplication注解中添加exclude属性即可:


@SpringBootApplication(exclude = {

DataSourceAutoConfiguration.class

})

public class TitanWebApplication {

public static void main(String[] args) {

SpringApplication.run(TitanWebApplication.class, args);

}

}

复制代码

然后在application.properties中配置多数据源连接信息:


# titan库

spring.datasource.titan-master.url=jdbc:mysql://X.X.X.X:port/titan?characterEncoding=UTF-8

spring.datasource.titan-master.username=

spring.datasource.titan-master.password=

spring.datasource.titan-master.driver-class-name=com.mysql.jdbc.Driver

# 连接池配置

# 省略

# 其它库

spring.datasource.db2.url=jdbc:mysql://X.X.X.X:port/titan2?characterEncoding=UTF-8

spring.datasource.db2.username=

spring.datasource.db2.password=

spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver

复制代码

由于我们禁掉了自动数据源配置,因些下一步就需要手动将这些数据源创建出来:


@Configuration

public class DataSourceConfig {

@Bean(name = "titanMasterDS")

@ConfigurationProperties(prefix = "spring.datasource.titan-master") // application.properteis中对应属性的前缀

public DataSource dataSource1() {

return DataSourceBuilder.create().build();

}

@Bean(name = "ds2")

@ConfigurationProperties(prefix = "spring.datasource.db2") // application.properteis中对应属性的前缀

public DataSource dataSource2() {

return DataSourceBuilder.create().build();

}

}

复制代码

接下来需要配置两个mybatis的SqlSessionFactory分别使用不同的数据源:


@Configuration

@MapperScan(basePackages = {"titan.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory1")

public class MybatisDbAConfig {

@Autowired

@Qualifier("titanMasterDS")

private DataSource ds1;

@Bean

public SqlSessionFactory sqlSessionFactory1() throws Exception {

SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

factoryBean.setDataSource(ds1); // 使用titan数据源, 连接titan库

return factoryBean.getObject();

}

@Bean

public SqlSessionTemplate sqlSessionTemplate1() throws Exception {

SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1()); // 使用上面配置的Factory

return template;

}

}

复制代码

经过上面的配置后,titan.mapper下的Mapper接口,都会使用titan数据源。同理可配第二个SqlSessionFactory:


@Configuration

@MapperScan(basePackages = {"other.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory2")

public class MybatisDbBConfig {

@Autowired

@Qualifier("ds2")

private DataSource ds2;

@Bean

public SqlSessionFactory sqlSessionFactory2() throws Exception {

SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

factoryBean.setDataSource(ds2);

return factoryBean.getObject();

}

@Bean

public SqlSessionTemplate sqlSessionTemplate2() throws Exception {

SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2());

return template;

}

}

复制代码

完成这些配置后,假设有2个Mapper titan.mapper.UserMapper和other.mapper.RoleMapper,使用前者时会自动连接titan库,后者连接ds2库。

动态数据源

使用动态数据源的初衷,是能在应用层做到读写分离,即在程序代码中控制不同的查询方法去连接不同的库。除了这种方法以外,数据库中间件也是个不错的选择,它的优点是数据库集群对应用来说只暴露为单库,不需要切换数据源的代码逻辑。

我们通过自定义注解 + AOP的方式实现数据源动态切换。

首先定义一个ContextHolder, 用于保存当前线程使用的数据源名:


public class DataSourceContextHolder {

public static final Logger log = LoggerFactory.getLogger(DataSourceContextHolder.class);

/**

* 默认数据源

*/

public static final String DEFAULT_DS = "titan-master";

private static final ThreadLocalcontextHolder = new ThreadLocal<>();

// 设置数据源名

public static void setDB(String dbType) {

log.debug("切换到{}数据源", dbType);

contextHolder.set(dbType);

}

// 获取数据源名

public static String getDB() {

return (contextHolder.get());

}

// 清除数据源名

public static void clearDB() {

contextHolder.remove();

}

}

复制代码

然后自定义一个javax.sql.DataSource接口的实现,这里只需要继承Spring为我们预先实现好的父类AbstractRoutingDataSource即可:


public class DynamicDataSource extends AbstractRoutingDataSource {

private static final Logger log = LoggerFactory.getLogger(DynamicDataSource.class);

@Override

protected Object determineCurrentLookupKey() {

log.debug("数据源为{}", DataSourceContextHolder.getDB());

return DataSourceContextHolder.getDB();

}

}

复制代码

创建动态数据源:


/**

* 动态数据源: 通过AOP在不同数据源之间动态切换

* @return

*/

@Bean(name = "dynamicDS1")

public DataSource dataSource() {

DynamicDataSource dynamicDataSource = new DynamicDataSource();

// 默认数据源

dynamicDataSource.setDefaultTargetDataSource(dataSource1());

// 配置多数据源

MapdsMap = new HashMap(5);

dsMap.put("titan-master", dataSource1());

dsMap.put("ds2", dataSource2());

dynamicDataSource.setTargetDataSources(dsMap);

return dynamicDataSource;

}

复制代码

自定义注释@DS用于在编码时指定方法使用哪个数据源:


@Retention(RetentionPolicy.RUNTIME)

@Target({

ElementType.METHOD

})

public @interface DS {

String value() default "titan-master";

}

复制代码

编写AOP切面,实现切换逻辑:


@Aspect

@Component

public class DynamicDataSourceAspect {

@Before("@annotation(DS)")

public void beforeSwitchDS(JoinPoint point){

//获得当前访问的class

Class 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);

// 判断是否存在@DS注解

if (method.isAnnotationPresent(DS.class)) {

DS annotation = method.getAnnotation(DS.class);

// 取出注解中的数据源名

dataSource = annotation.value();

}

} catch (Exception e) {

e.printStackTrace();

}

// 切换数据源

DataSourceContextHolder.setDB(dataSource);

}

@After("@annotation(DS)")

public void afterSwitchDS(JoinPoint point){

DataSourceContextHolder.clearDB();

}

}

复制代码

完成上述配置后,在先前SqlSessionFactory配置中指定使用DynamicDataSource就可以在Service中愉快的切换数据源了:


@Autowired

private UserAModelMapper userAMapper;

@DS("titan-master")

public String ds1() {

return userAMapper.selectByPrimaryKey(1).getName();

}

@DS("ds2")

public String ds2() {

return userAMapper.selectByPrimaryKey(1).getName();

}

复制代码

总结

以上所述是小编给大家介绍的Spring Boot + Mybatis多数据源和动态数据源配置方法,希望对大家有所帮助,了解更多内容,请关注职坐标编程语言JAVA频道!


本文由 @职坐标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论
本文作者 联系TA

擅长针对企业软件开发的产品设计及开发的细节与流程设计课程内容。座右铭:大道至简!

  • 370
    文章
  • 22916
    人气
  • 87%
    受欢迎度

已有23人表明态度,87%喜欢该老师!

进入TA的空间
求职秘籍 直通车
  • 索取资料 索取资料 索取资料
  • 答疑解惑 答疑解惑 答疑解惑
  • 技术交流 技术交流 技术交流
  • 职业测评 职业测评 职业测评
  • 面试技巧 面试技巧 面试技巧
  • 高薪秘笈 高薪秘笈 高薪秘笈
TA的其他文章 更多>>
WEB前端必须会的基本知识题目
经验技巧 93% 的用户喜欢
Java语言中四种遍历List的方法总结(推荐)
经验技巧 91% 的用户喜欢
Java语言之SHA-256加密的两种实现方法详解
经验技巧 75% 的用户喜欢
java语言实现把两个有序数组合并到一个数组的实例
经验技巧 75% 的用户喜欢
通过Java语言代码来创建view的方法
经验技巧 80% 的用户喜欢
其他海同师资 更多>>
吕益平
吕益平 联系TA
熟悉企业软件开发的产品设计及开发
孔庆琦
孔庆琦 联系TA
对MVC模式和三层架构有深入的研究
周鸣君
周鸣君 联系TA
擅长Hadoop/Spark大数据技术
范佺菁
范佺菁 联系TA
擅长Java语言,只有合理的安排和管理时间你才能做得更多,行得更远!
金延鑫
金延鑫 联系TA
擅长与学生或家长及时有效沟通
经验技巧30天热搜词 更多>>

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程