Spring Boot + MyBatis-Plus实现数据库读写分离
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
@Configuration
@MapperScan(basePackages = "com.example.mapper.read", sqlSessionFactoryRef = "readSqlSessionFactory")
public class MyBatisConfig {
@Bean(name = "readSqlSessionFactory")
public SqlSessionFactory readSqlSessionFactory(DataSource readDataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(readDataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/read/*.xml"));
return factoryBean.getObject();
}
// 同上,为写数据源配置SqlSessionFactory和MapperScan
}
在这个配置类中,我们定义了一个读数据源的SqlSessionFactory
和MapperScan
。写数据源同理,可以创建相应的writeSqlSessionFactory
和writeMapperScan
。然后在DataSourceConfig
中配置好数据源,并注入到对应的SqlSessionFactory
中。这样,MyBatis-Plus就可以根据不同的@MapperScan
和SqlSessionFactory
区分读写请求,实现数据库的读写分离。
评论已关闭