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

/*** 主从配置

*

*@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;

}

}

你可能感兴趣的:(springboot实现mysql主从_基于 SpringBoot,来实现MySQL读写分离技术)