springboot实现mysql主从_基于 SpringBoot,来实现MySQL读写分离技术

发布时间:2022-11-17 17:00

/*** 主从配置

*

*@authorwyq*/@Configuration

@MapperScan(basePackages= "com.wyq.mysqlreadwriteseparate.mapper", sqlSessionTemplateRef = "sqlTemplate")public classDataSourceConfig {/*** 主库*/@Bean

@ConfigurationProperties(prefix= "spring.datasource.master")publicDataSource master() {returnDruidDataSourceBuilder.create().build();

}/*** 从库*/@Bean

@ConfigurationProperties(prefix= "spring.datasource.slave")publicDataSource slaver() {returnDruidDataSourceBuilder.create().build();

}/*** 实例化数据源路由*/@Beanpublic DataSourceRouter dynamicDB(@Qualifier("master") DataSource masterDataSource,

@Autowired(required= false) @Qualifier("slaver") DataSource slaveDataSource) {

DataSourceRouter dynamicDataSource= newDataSourceRouter();

Map targetDataSources = new HashMap<>();

targetDataSources.put(DataSourceEnum.MASTER.getDataSourceName(), masterDataSource);if (slaveDataSource != null) {

targetDataSources.put(DataSourceEnum.SLAVE.getDataSourceName(), slaveDataSource);

}

dynamicDataSource.setTargetDataSources(targetDataSources);

dynamicDataSource.setDefaultTargetDataSource(masterDataSource);returndynamicDataSource;

}/*** 配置sessionFactory

*@paramdynamicDataSource

*@return*@throwsException*/@Beanpublic SqlSessionFactory sessionFactory(@Qualifier("dynamicDB") DataSource dynamicDataSource) throwsException {

SqlSessionFactoryBean bean= newSqlSessionFactoryBean();

bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper.xml"));

bean.setDataSource(dynamicDataSource);returnbean.getObject();

}/*** 创建sqlTemplate

*@paramsqlSessionFactory

*@return

*/@Beanpublic SqlSessionTemplate sqlTemplate(@Qualifier("sessionFactory") SqlSessionFactory sqlSessionFactory) {return newSqlSessionTemplate(sqlSessionFactory);

}/*** 事务配置

*

*@paramdynamicDataSource

*@return

*/@Bean(name= "dataSourceTx")public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("dynamicDB") DataSource dynamicDataSource) {

DataSourceTransactionManager dataSourceTransactionManager= newDataSourceTransactionManager();

dataSourceTransactionManager.setDataSource(dynamicDataSource);returndataSourceTransactionManager;

}

}

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号