使用Mybatis-Plus实现动态多数据源切换

摘要: 本文将介绍如何使用Mybatis-Plus配合Spring Boot来实现动态多数据源的切换。我们将讨论依赖引入、配置修改、自定义数据源提供者、配置类编写、数据源工具类实现以及AOP切面编程的应用。

一、引言

在现代的企业级应用中,常常需要根据不同的业务场景动态地切换数据源。Mybatis-Plus提供了一个基于Spring Boot的快速集成多数据源的启动器,dynamic-datasource-spring-boot-starter,以简化这一过程。

二、依赖引入

首先,在项目的pom.xml文件中引入所需的依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

三、修改yml配置

接下来,在application.yml件中配置数据源:

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    dynamic:
      primary: master
      strict: false
      datasource:
        master:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/master_db
          username: root
          password: pass

四、实现自定义数据源提供者

我们可以通过继承AbstractJdbcDataSourceProvider类来实现自定义的数据源提供者:

public class CustomDynamicDataSourceProvider extends AbstractJdbcDataSourceProvider {
	
	    public CustomDynamicDataSourceProvider(String driverClassName, String url, String username, String password) {
	        super(driverClassName, url, username, password);
	    }
	
	    @Override
	    protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
	        Map<String, DataSourceProperty> map = new HashMap<>();
	        ResultSet rs = statement.executeQuery(GlobalConstant.DB_QUERY);
	        /**
	         * 获取信息
	         */
	        while (rs.next()) {
	            String dbName = rs.getString("db_name");
	            String dbIp = rs.getString("db_ip");
	            String dbIpPort = rs.getString("db_ip_port");
	            String jdbcUrl = GlobalConstant.DB_URL
	                    .replace("{dbIp}", dbIp)
	                    .replace("{dbPort}", dbIpPort)
	                    .replace("{dbName}", dbName);
	            String dbUser = rs.getString("db_user");
	            String dbPwd = rs.getString("db_pwd");
	            String key = rs.getString("id");
	            String name = rs.getString("name");
	            DataSourceProperty dataSourceProperty = new DataSourceProperty();
	            dataSourceProperty
	                    .setDriverClassName(GlobalConstant.DB_DRIVER)
	                    .setUrl(jdbcUrl)
	                    .setUsername(dbUser)
	                    .setPassword(dbPwd)
	                    .setPoolName(name);
	            map.put(key, dataSourceProperty);
	        }
	        return map;
	  }
}

五、添加DataSourceConfiguration配置类

@Primary
@Configuration
public class DataSourceConfiguration {

    @Autowired
    private DynamicDataSourceProperties properties;

    @Value("${spring.datasource.dynamic.primary}")
    private String masterName;

    @Bean
    public DynamicDataSourceProvider customDynamicDataSourceProvider() {
        Map<String, DataSourceProperty> datasource = properties.getDatasource();
        DataSourceProperty property = datasource.get(masterName);
        return new CustomDynamicDataSourceProvider(property.getDriverClassName(), property.getUrl(), property.getUsername(), property.getPassword());
    }
}

六、实现数据源工具类DataSourceService

@Service
public class DataSourceService {

    @Autowired
    private DynamicRoutingDataSource dataSource;

    @Autowired
    private HikariDataSourceCreator dataSourceCreator;

    public DataSource get(String key){
        return dataSource.getDataSource(key);
    }

    public Set<String> getList(){
        return dataSource.getDataSources().keySet();
    }

    public Set<String> add(DataSourceProperty dsp, String key) {
        dsp.setDriverClassName(GlobalConstant.DB_DRIVER);
        DataSource creatorDataSource = dataSourceCreator.createDataSource(dsp);
        dataSource.addDataSource(key, creatorDataSource);
        return dataSource.getDataSources().keySet();
    }

    public Boolean remove(String name) {
        dataSource.removeDataSource(name);
        return Boolean.TRUE;
    }
}

七、通过AOP动态切换数据源

最后,我们使用AOP来实现数据源的动态切换:

@Slf4j
@Aspect
@Component
public class DataSourceAspect {

    @Autowired
    private DataSourceService sourceService;

    @Pointcut("within(com.baomidou.mybatisplus.extension.service.IService+)")
    public void dataSourcePointcut() {}

    @Before("dataSourcePointcut()")
    public void doBefore(JoinPoint joinPoint) {
        String org = ThreadLocalContext.getOrg();
        String master = "master";
        if (StringUtils.isEmpty(org) || "null".equals(org) || NumberConstant.STRING_ZERO.equals(org) || master.equals(org)) {
            String peek = DynamicDataSourceContextHolder.peek();
            if (master.equals(peek)) {
                return;
            }
            DynamicDataSourceContextHolder.push(master);
        } else {
            Set<String> set = sourceService.getList();
            if (!set.contains(org)) {
                throw new BusinessException("当前机构未配置数据源,请联系管理员!");
            }
            try {
                DynamicDataSourceContextHolder.push(org);
            } catch (Exception e) {
                throw new BusinessException("当前机构未配置数据源,请联系管理员!");
            }
        }
        Class<?> clazz = joinPoint.getTarget().getClass();
        String methodName = joinPoint.getSignature().getName();
        log.info(clazz + "类-" + methodName + "方法-" + org + "数据源");
    }

    @AfterReturning("dataSourcePointcut()")
    public void doAfter(JoinPoint joinPoint) {
        DynamicDataSourceContextHolder.poll();
    }
}

自定义的当前线程请求上线文ThreadLocalContext

public class ThreadLocalContext {

	private static ThreadLocal<String> threadLocalOrg = new ThreadLocal<String>();
	
	public static String getOrg() {
		return threadLocalOrg.get();
	}

	public static void setOrg(String org) {
		threadLocalOrg.set(org);
	}

	public static void remove() {
		threadLocalOrg.remove();
	}
}

在请求拦截器里面添加线程请求的机构

@Component
public class ManageInterceptorHandler extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    	// ...
		ThreadLocalContext.setOrg(authToken.getOrgId());
		return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
        // ...
    }
}

八、总结

通过上述步骤,我们已经成功地实现了Mybatis-Plus配合Spring Boot的动态多数据源切换。这种配置方式既灵活又强大,非常适合需要处理多个数据库的现代应用程序。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
SpringBoot是一个高效的Java开发框架,它能够方便开发者集成MyBatis-Plus实现多数据源动态切换以及支持分页查询。MyBatis-Plus是一种优秀的ORM框架,它增强了MyBatis的基础功能,并支持通过注解方式进行映射。 首先,我们需要在pom.xml文件中添加MyBatis-Plus和数据库连接池的依赖。在application.yml文件中,我们需要配置多个数据源和对应的连接信息。我们可以定义一个DataSourceConfig用于获取多个数据源,然后在Mapper配置类中使用@MapperScan(basePackages = {"com.test.mapper"})来扫描Mapper接口。 要实现动态切换数据源,我们可以自定义一个注解@DataSource来标注Mapper接口或方法,然后使用AOP拦截数据源切换实现动态切换。在实现分页查询时,我们可以使用MyBatis-Plus提供的分页插件来支持分页查询。 代码示例: 1. 在pom.xml文件中添加MyBatis-Plus和数据库连接池的依赖。 ``` <dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.4</version> </dependency> </dependencies> ``` 2. 在application.yml文件中配置多个数据源和对应的连接信息。以两个数据源为例: ``` spring: datasource: druid: db1: url: jdbc:mysql://localhost:3306/db1 username: root password: root driver-class-name: com.mysql.jdbc.Driver db2: url: jdbc:mysql://localhost:3306/db2 username: root password: root driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # 指定默认数据源 primary: db1 ``` 3. 定义一个DataSourceConfig用于获取多个数据源。 ``` @Configuration public class DataSourceConfig { @Bean("db1") @ConfigurationProperties("spring.datasource.druid.db1") public DataSource dataSource1() { return DruidDataSourceBuilder.create().build(); } @Bean("db2") @ConfigurationProperties("spring.datasource.druid.db2") public DataSource dataSource2() { return DruidDataSourceBuilder.create().build(); } @Bean @Primary public DataSource dataSource() { DynamicDataSource dynamicDataSource = new DynamicDataSource(); // 设置数据源映射关系 Map<Object, Object> dataSourceMap = new HashMap<>(); dataSourceMap.put("db1", dataSource1()); dataSourceMap.put("db2", dataSource2()); dynamicDataSource.setTargetDataSources(dataSourceMap); // 设置默认数据源 dynamicDataSource.setDefaultTargetDataSource(dataSource1()); return dynamicDataSource; } } ``` 4. 在Mapper配置类中使用@MapperScan(basePackages = {"com.test.mapper"})来扫描Mapper接口,并使用@DataSource注解来标注Mapper接口或方法。 ``` @Configuration @MapperScan(basePackages = {"com.test.mapper"}) public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } } @DataSource("db1") public interface UserMapper { @Select("select * from user where id = #{id}") User selectById(@Param("id") Long id); } ``` 5. 实现AOP拦截数据源切换。 ``` @Aspect @Component public class DataSourceAspect { @Before("@annotation(ds)") public void beforeSwitchDataSource(JoinPoint point, DataSource ds) { String dataSource = ds.value(); if (!DynamicDataSourceContextHolder.containDataSourceKey(dataSource)) { System.err.println("数据源 " + dataSource + " 不存在,使用默认数据源"); } else { System.out.println("使用数据源:" + dataSource); DynamicDataSourceContextHolder.setDataSourceKey(dataSource); } } } ``` 6. 分页查询的使用示例: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override @DataSource("db1") public IPage<User> getUserList(int pageNum, int pageSize) { Page<User> page = new Page<>(pageNum, pageSize); return userMapper.selectPage(page, null); } } ``` 以上就是SpringBoot整合MyBatis-Plus实现多数据源动态切换和分页查询的具体实现过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AbelEthan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值