springboot+mybatis-plus+quartz多数据源操作,亲测可用

本文介绍了在SpringBoot项目中如何使用Mybatis-Plus和Quartz实现多数据源操作,特别是如何解决Quartz定时任务默认连接主库的问题。通过自定义AbstractRoutingDataSource,动态改变线程中的数据源,并利用AOP实现注解切换,确保计时器数据源与主程序数据源分离。关键步骤包括数据源配置、AOP注解切换和SqlSessionFactory的设置。
摘要由CSDN通过智能技术生成

背景:
开发项目中,使用到quartz,想把计时器的数据源和主程序的数据源分离,刚开始选择的是通过mybatis-plus提供动态数据源,可是发现在quartz启动时候会默认的将数据计时器相关的11张表信息建立到主库,经过研究,最后只能手写一个动态数据源分配的方法。
开发步骤

  1. 依赖
    采用springboot的默认依赖,这里不做表述。如果需要quartz计时操作就专门加个quartz的依赖
  2. 配置yml文件
    springboot直接在application中写,两个数据源配置是必须的
spring:
  datasource:
    druid:
      think-users:
        url: jdbc:mysql://localhost:3306/think_users?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
        driverClassName: com.mysql.cj.jdbc.Driver
        username: root
        password: 123456
      think-quartz:
        url: jdbc:mysql://localhost:3306/think_quartz?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
        driverClassName: com.mysql.cj.jdbc.Driver
        username: root
        password: 123456
      aop-patterns: com.unicom.xz.integrated.*
      stat-view-servlet:
        enabled: true
        login-username: admin
        login-password: admin
        reset-enable: false
      web-stat-filter:
        enabled: true
      filters: stat,wall,slf4j
      filter:
        stat:
          slow-sql-millis: 1000
          log-slow-sql: true
        wall:
          enabled: true
  quartz:
    properties:
      org:
        quartz:
          scheduler:
            # 集群名,区分同一系统的不同实例,若使用集群功能,则每一个实例都要使用相同的名字
            instanceName: clusteredScheduler
            # 若是集群下,每个instanceId必须唯一
            instanceId: AUTO
          threadPool:
            #一般使用这个便可
            class: org.quartz.simpl.SimpleThreadPool
            #线程数量,不会动态增加
            threadCount: 10
            threadPriority: 5
            threadsInheritContextClassLoaderOfInitializingThread: true
          jobStore:
            #选择JDBC的存储方式
            class: org.quartz.impl.jdbcjobstore.JobStoreTX
            driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
            tablePrefix: QRTZ_
            useProperties: false
            isClustered: true
            clusterCheckinInterval: 15000
          dataSource:
            qzDs:
              provider: hikaricp
              driver: com.mysql.cj.jdbc.Driver
              URL: jdbc:mysql://localhost
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Springboot+MyBatis-Plus实现多租户动态数据源模式是一种在Spring Boot框架下使用MyBatis-Plus插件实现多租户数据隔离的方法。它可以根据不同的租户动态切换数据源,实现不同租户之间的数据隔离。 实现多租户动态数据源模式的关键是配置多个数据源,并在运行时根据租户信息动态选择使用哪个数据源。以下是一个简单的示例代码: 1. 首先,需要在pom.xml文件中添加Druid数据源的依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.21</version> </dependency> ``` 2. 在application.properties或application.yml文件中配置多个数据源的连接信息,例如: ```yaml spring.datasource.master.url=jdbc:mysql://localhost:3306/master_db spring.datasource.master.username=root spring.datasource.master.password=123456 spring.datasource.tenant1.url=jdbc:mysql://localhost:3306/tenant1_db spring.datasource.tenant1.username=root spring.datasource.tenant1.password=123456 spring.datasource.tenant2.url=jdbc:mysql://localhost:3306/tenant2_db spring.datasource.tenant2.username=root spring.datasource.tenant2.password=123456 ``` 3. 创建一个多租户数据源配置类,用于动态选择数据源。可以使用ThreadLocal来保存当前租户的标识,然后根据标识选择对应的数据源。以下是一个简单的示例: ```java @Configuration public class MultiTenantDataSourceConfig { @Autowired private DataSourceProperties dataSourceProperties; @Bean @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource masterDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.tenant1") public DataSource tenant1DataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.tenant2") public DataSource tenant2DataSource() { return DataSourceBuilder.create().build(); } @Bean @Primary public DataSource dynamicDataSource() { DynamicDataSource dynamicDataSource = new DynamicDataSource(); Map<Object, Object> dataSourceMap = new HashMap<>(); dataSourceMap.put("master", masterDataSource()); dataSourceMap.put("tenant1", tenant1DataSource()); dataSourceMap.put("tenant2", tenant2DataSource()); dynamicDataSource.setTargetDataSources(dataSourceMap); dynamicDataSource.setDefaultTargetDataSource(masterDataSource()); return dynamicDataSource; } @Bean public SqlSessionFactory sqlSessionFactory(DataSource dynamicDataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dynamicDataSource); return sessionFactory.getObject(); } @Bean public PlatformTransactionManager transactionManager(DataSource dynamicDataSource) { return new DataSourceTransactionManager(dynamicDataSource); } } ``` 4. 创建一个多租户数据源切换器,用于在每次数据库操作前切换数据源。以下是一个简单的示例: ```java public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return TenantContext.getTenantId(); } } ``` 5. 创建一个租户上下文类,用于保存当前租户的标识。以下是一个简单的示例: ```java public class TenantContext { private static final ThreadLocal<String> CONTEXT = new ThreadLocal<>(); public static void setTenantId(String tenantId) { CONTEXT.set(tenantId); } public static String getTenantId() { return CONTEXT.get(); } public static void clear() { CONTEXT.remove(); } } ``` 6. 在需要切换数据源的地方,调用TenantContext.setTenantId()方法设置当前租户的标识。例如: ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users") public List<User> getUsers() { TenantContext.setTenantId("tenant1"); List<User> users = userService.getUsers(); TenantContext.clear(); return users; } } ``` 通过以上步骤,就可以实现Springboot+MyBatis-Plus的多租户动态数据源模式了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值