Spring-Boot + Mybatis 多数据源配置

简介: Spring-Boot + Mybatis 多数据源


折腾了一天,终于完成了多数据源的配置,记录在这里!

1,先上SpringBoot 基础配置



        ①,系统引入了Security的包,但是没有配置Security相关信息,在启动时会打印警告log,故这里排除SecurityAutoConfiguration这个类


2,配置两个数据源



@Configuration
public class DataBaseConfig implements EnvironmentAware {

	private RelaxedPropertyResolver dbPropertyResolver;

	private static final Logger logger = LoggerFactory.getLogger(EnvironmentAware.class);

	@Override
	public void setEnvironment(Environment environment) {
		dbPropertyResolver = new RelaxedPropertyResolver(environment,"jdbc.");
	}


	/**
	 * 写库
	 * @return
	 */
	@Bean(name="writeDataSource", destroyMethod = "close", initMethod="init")
	@Primary
	public DataSource writeDataSource() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl(dbPropertyResolver.getProperty("url"));
		datasource.setDriverClassName(dbPropertyResolver.getProperty("driverClass"));
		datasource.setUsername(dbPropertyResolver.getProperty("username"));
		datasource.setPassword(dbPropertyResolver.getProperty("password"));
		return datasource;
	}

	/**
	 * 读库
	 * @return
	 */
	@Bean(name="readDataSource", destroyMethod = "close", initMethod="init")
	public DataSource readOneDataSource() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl(dbPropertyResolver.getProperty("url"));
		datasource.setDriverClassName(dbPropertyResolver.getProperty("driverClassName"));
		datasource.setUsername(dbPropertyResolver.getProperty("username"));
		datasource.setPassword(dbPropertyResolver.getProperty("password"));
		return datasource;
	}
}

②,将写库作为默认主数据源,在注入时,若没有指定该注入哪一个数据源,默认注入使用写库数据源



3,配置只读数据源与Mybatis的配置信息



@Configuration
@EnableTransactionManagement
@AutoConfigureAfter(WriteMybatisConfig.class)
public class ReadMybatisConfig implements EnvironmentAware {

	/**
	 * 日志记录器
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(ReadMybatisConfig.class);

	private RelaxedPropertyResolver mybatisPropertyResolver;

	/**
	 * 获取配置信息
	 * @param environment
	 */
	@Override
	public void setEnvironment(Environment environment) {
		mybatisPropertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");
	}

	//从库数据源
	@Resource(name = "readDataSource")
	private DataSource readDataSource;

	/**
	 * 只读sqlSessionFactory
	 * @return
	 */
	@Bean(name = "readSqlSessionFactory")
	public SqlSessionFactory readSqlSessionFactory() {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(readDataSource);
		bean.setTypeAliasesPackage(mybatisPropertyResolver.getProperty("typeAliasesPackage"));

		//分页插件
		PageHelper pageHelper = new PageHelper();
		Properties properties = new Properties();
		properties.setProperty("reasonable", "true");
		properties.setProperty("supportMethodsArguments", "true");
		properties.setProperty("returnPageInfo", "check");
		properties.setProperty("params", "count=countSql");
		pageHelper.setProperties(properties);
		bean.setPlugins(new Interceptor[]{pageHelper});

		//添加mybatis配置文件
		PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
		bean.setConfigLocation(resourceResolver.getResource(mybatisPropertyResolver.getProperty("configLocation")));
		try {
			bean.setMapperLocations(resourceResolver.getResources(mybatisPropertyResolver.getProperty("mapperLocations")));
			return bean.getObject();
		} catch (IOException e) {
			LOGGER.error("获取mapper资源出现异常",e);
			throw new RuntimeException("获取mapper资源出现异常",e);
		} catch (Exception e){
			LOGGER.error("初始化sqlSessionFactory时出现异常",e);
			throw new RuntimeException("初始化sqlSessionFactory时出现异常",e);
		}
	}

}

4,配置写数据源与Mybatis的配置



@Configuration
@EnableTransactionManagement
@AutoConfigureAfter
public class WriteMybatisConfig implements EnvironmentAware {
    public static final Logger LOGGER = LoggerFactory.getLogger(WriteMybatisConfig.class);

	private RelaxedPropertyResolver mybatisPropertyResolver;

	@Override
	public void setEnvironment(Environment environment) {
		mybatisPropertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");
	}

	//写库
	@Resource(name = "writeDataSource")
    private DataSource writeDataSource;

	/**
	 * 可读可写sqlSessionFactory
	 * @return
	 */
    @Bean(name = "writeSqlSessionFactory")
    public SqlSessionFactory writeSqlSessionFactory() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(writeDataSource);
        bean.setTypeAliasesPackage(mybatisPropertyResolver.getProperty("typeAliasesPackage"));

        //分页插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        bean.setPlugins(new Interceptor[]{pageHelper});

        //添加mybatis配置文件
		PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
		bean.setConfigLocation(resourceResolver.getResource(mybatisPropertyResolver.getProperty("configLocation")));
        try {
			bean.setMapperLocations(resourceResolver.getResources(mybatisPropertyResolver.getProperty("mapperLocations")));
			return bean.getObject();
        } catch (IOException e) {
			LOGGER.error("获取mapper资源出现异常",e);
            throw new RuntimeException("获取mapper资源出现异常",e);
        } catch (Exception e){
			LOGGER.error("初始化sqlSessionFactory时出现异常",e);
			throw new RuntimeException("初始化sqlSessionFactory时出现异常",e);
		}
    }

	/**
	 * 因为当前项目中有
	 * @return
	 */
	@Bean(name = "writeTransactionManager")
	public DataSourceTransactionManager writeTransactionManager() {
		DataSourceTransactionManager manager = new DataSourceTransactionManager(writeDataSource);
		return manager;
	}


}


注意,写数据源对应的持久化操作需要用到事务,所以配置了 DataSourceTransactionManager


5,配置Mybatis的Mapper扫描器



@Configuration
public class MybatisMapperScannerConfig {

	/**
	 * 扫描读写模式-mapper,只有在basePackage包下且继承自BaseWriterMapper的mapper才会被扫描到
	 * @return
	 */
	@Bean(name = "writeMapperScanner")
	public MapperScannerConfigurer writeMapperScanner(){
		MapperScannerConfigurer configurer = new MapperScannerConfigurer();
		configurer.setBasePackage("com.llktop.dao");
		configurer.setMarkerInterface(BaseWriteMapper.class);
		configurer.setSqlSessionFactoryBeanName("writeSqlSessionFactory");
		return configurer;
	}

	/**
	 * 扫描只读模式-mapper,只有在basePackage包下且继承自BaseReadMapper的mapper才会被扫描到
	 * @return
	 */
	@Bean(name = "readMapperScanner")
	public MapperScannerConfigurer readMapperScanner(){
		MapperScannerConfigurer configurer = new MapperScannerConfigurer();
		configurer.setBasePackage("com.llktop.dao");
		configurer.setMarkerInterface(BaseReadMapper.class);
		configurer.setSqlSessionFactoryBeanName("readSqlSessionFactory");
		return configurer;
	}
}

注意,这里多配置了一个叫MarkerInterface的属性,目的是,所有的mapper中只有继承自BaseWriteMapper这个类的Mapper会走写数据源,而所有继承自ReadMapper的Mapper会走读数据源


这样,就做到了多套数据源,可以配合Mysql读写分离进行使用!



目录
相关文章
|
25天前
|
XML Java 测试技术
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
118 26
|
2月前
|
Java Spring
【Spring】方法注解@Bean,配置类扫描路径
@Bean方法注解,如何在同一个类下面定义多个Bean对象,配置扫描路径
184 73
|
28天前
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
123 29
|
1月前
|
监控 Java 数据库连接
Spring c3p0配置详解
在Spring项目中配置C3P0数据源,可以显著提高数据库连接的效率和应用程序的性能。通过合理的配置和优化,可以充分发挥C3P0的优势,满足不同应用场景的需求。希望本文的详解和示例代码能为开发者提供清晰的指导,帮助实现高效的数据库连接管理。
72 10
|
1月前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
64 2
|
1月前
|
SQL JavaScript Java
Spring Boot 3 整合 Mybatis-Plus 实现数据权限控制
本文介绍了如何在Spring Boot 3中整合MyBatis-Plus实现数据权限控制,通过使用MyBatis-Plus提供的`DataPermissionInterceptor`插件,在不破坏原有代码结构的基础上实现了细粒度的数据访问控制。文中详细描述了自定义注解`DataScope`的使用方法、`DataPermissionHandler`的具体实现逻辑,以及根据用户的不同角色和部门动态添加SQL片段来限制查询结果。此外,还展示了基于Spring Boot 3和Vue 3构建的前后端分离快速开发框架的实际应用案例,包括项目的核心功能模块如用户管理、角色管理等,并提供Gitee上的开源仓库
294 11
|
1月前
|
缓存 NoSQL Java
Mybatis学习:Mybatis缓存配置
MyBatis缓存配置包括一级缓存(事务级)、二级缓存(应用级)和三级缓存(如Redis,跨JVM)。一级缓存自动启用,二级缓存需在`mybatis-config.xml`中开启并配置映射文件或注解。集成Redis缓存时,需添加依赖、配置Redis参数并在映射文件中指定缓存类型。适用于查询为主的场景,减少增删改操作,适合单表操作且表间关联较少的业务。
|
2月前
|
Java Spring
【Spring配置相关】启动类为Current File,如何更改
问题场景:当我们切换类的界面的时候,重新启动的按钮是灰色的,不能使用,并且只有一个Current File 项目,下面介绍两种方法来解决这个问题。
|
2月前
|
Java Spring
【Spring配置】idea编码格式导致注解汉字无法保存
问题一:对于同一个项目,我们在使用idea的过程中,使用汉字注解完后,再打开该项目,汉字变成乱码问题二:本来a项目中,汉字注解调试好了,没有乱码了,但是创建出来的新的项目,写的注解又成乱码了。
|
2月前
|
Java Spring
【Spring配置】创建yml文件和properties或yml文件没有绿叶
本文主要针对,一个项目中怎么创建yml和properties两种不同文件,进行配置,和启动类没有绿叶标识进行解决。