首頁 > 軟體

SpringBoot整合Mybatis實現多資料來源設定與跨資料來源事務範例

2022-11-28 22:01:55

Pom依賴

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
    <relativePath/>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.2.14</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.2</version>
    </dependency>
    <!--   分頁外掛     -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
</dependencies>

application.yml

# 資料來源
spring:
  datasource:
    # master主資料來源設定
    master:
      driverClassName: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/ds1?characterEncoding=UTF-8&serverTimezone=GMT%2B8
      username: root
      password: root
    # cluster從資料來源設定
    cluster:
      driverClassName: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/ds2?characterEncoding=UTF-8&serverTimezone=GMT%2B8
      username: root
      password: root
#pagehelper分頁外掛設定
pagehelper:
  master:
    helper-dialect: mysql  #設定資料庫型別
    reasonable: true  #開啟合理化:頁碼<=0 查詢第一頁,頁碼>=總頁數查詢最後一頁
    support-methods-arguments: true  #支援通過 Mapper 介面引數來傳遞分頁引數
    params: count=countsql

多資料來源設定

Java程式碼方式建立主從資料來源設定。 使用@Primary: 用於指定bean的注入優先順序。被@Primary修飾的bean物件優先注入

MasterDataSourceConfig

/**
 * @ClassName: MasterDataSourceConfig
 * @Description: mysql主庫設定類
 */
@Configuration
@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE,sqlSessionTemplateRef = "masterSqlSessionTemplate")
public class MasterDataSourceConfig {
    /**
     * 設定掃描包的路徑
     */
    public static final String PACKAGE = "cn.zysheep.dao.master";
    /**
     * Mapper組態檔路徑
     */
    public static final String MAPPER_LOCATION = "classpath*:mapper/master/*.xml";
    /**
     * 實體別名
     */
    public static final String ENTITY_ALIASES = "cn.zysheep.entity";
    @Value("${spring.datasource.master.driverClassName}")
    private String driverClassName;
    @Value("${spring.datasource.master.url}")
    private String url;
    @Value("${spring.datasource.master.username}")
    private String user;
    @Value("${spring.datasource.master.password}")
    private String password;
    @Value("${pagehelper.master.helper-dialect}")
    private String helperDialect;
    @Value("${pagehelper.master.reasonable}")
    private String reasonable;
    /**
     * 建立資料來源
     * @return DataSource
     * @Primary: 用於指定bean的注入優先順序。被@Primary修飾的bean物件優先注入
     */
    @Bean(name = "masterDataSource")
    @Primary
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }
    /**
     * 建立工廠
     *@param dataSource
     *@throws Exception
     *@return SqlSessionFactory
     */
    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        sessionFactory.setTypeAliasesPackage(ENTITY_ALIASES);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        // 欄位值為空也可以插入
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setCallSettersOnNulls(true);
        // mybatis log
        configuration.setLogImpl(StdOutImpl.class);
        sessionFactory.setConfiguration(configuration);
        PageInterceptor pageInterceptor = new PageInterceptor();
        // 分頁設定
        Properties p = new Properties();
        p.setProperty("helperDialect", helperDialect);
        p.setProperty("reasonable", reasonable);
        pageInterceptor.setProperties(p);
        sessionFactory.setPlugins(pageInterceptor);
        return sessionFactory.getObject();
    }
    /**
     * 建立事務
     *@param dataSource
     *@return DataSourceTransactionManager
     */
    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    /**
     * 建立模板
     *@param sqlSessionFactory
     *@return SqlSessionTemplate
     */
    @Bean(name = "masterSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

ClusterDataSourceConfig

/**
 * @ClassName: DataSourceConfig
 * @Description: mysql從庫設定類
 */
@Configuration
@MapperScan(basePackages = ClusterDataSourceConfig.PACKAGE,sqlSessionTemplateRef = "clusterSqlSessionTemplate")
public class ClusterDataSourceConfig {
    /**
     * 設定掃描包的路徑
     */
    public static final String PACKAGE = "cn.zysheep.dao.cluster";
    /**
     * Mapper組態檔路徑
     */
    public static final String MAPPER_LOCATION = "classpath*:mapper/cluster/*.xml";
    /**
     * 實體別名
     */
    public static final String ENTITY_ALIASES = "cn.zysheep.entity";
    @Value("${spring.datasource.cluster.driverClassName}")
    private String driverClassName;
    @Value("${spring.datasource.cluster.url}")
    private String url;
    @Value("${spring.datasource.cluster.username}")
    private String user;
    @Value("${spring.datasource.cluster.password}")
    private String password;
    @Value("${pagehelper.master.helper-dialect}")
    private String helperDialect;
    @Value("${pagehelper.master.reasonable}")
    private String reasonable;
    /**
     * 建立資料來源
     *@return DataSource
     */
    @Bean(name = "clusterDataSource")
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }
    /**
     * 建立工廠
     *@param dataSource
     *@throws Exception
     *@return SqlSessionFactory
     */
    @Bean(name = "clusterSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        sessionFactory.setTypeAliasesPackage(ENTITY_ALIASES);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        // 欄位值為空也可以插入
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setCallSettersOnNulls(true);
        // mybatis log
        configuration.setLogImpl(StdOutImpl.class);
        sessionFactory.setConfiguration(configuration);
        PageInterceptor pageInterceptor = new PageInterceptor();
        // 分頁設定
        Properties p = new Properties();
        p.setProperty("helperDialect", helperDialect);
        p.setProperty("reasonable", reasonable);
        pageInterceptor.setProperties(p);
        sessionFactory.setPlugins(pageInterceptor);
        return sessionFactory.getObject();
    }
    /**
     * 建立事務管理器
     *@param dataSource
     *@return DataSourceTransactionManager
     */
    @Bean(name = "clusterTransactionManager")
    public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier("clusterDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    /**
     * 建立模板
     *@param sqlSessionFactory
     *@return SqlSessionTemplate
     */
    @Bean(name = "clusterSqlSessionTemplate")
    public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("clusterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

啟動類

啟動類新增@EnableTransactionManagement註解,開啟註解事務

@EnableTransactionManagement
@SpringBootApplication(exclude = PageHelperAutoConfiguration.class)
public class MultiDataSourceApplication {
    public static void main(String[] args) {
        SpringApplication.run(MultiDataSourceApplication.class, args);
    }
}

使用

在service層類或者方法上新增@Transactional註解。並指定屬性 事務管理器transactionManager的值,根據使用不同的資料來源,選擇不同的資料事務管理器

@Transactional(transactionManager = "masterTransactionManager")
public void insertUser() {
    // TODO 新增使用者業務操作
}
@Transactional(transactionManager = "clusterTransactionManager")
public void listUser() {
    // TODO 查詢使用者業務操作
}

思考: @Transactional只能指定一個事務管理器,並且註解不允許重複,所以就只能使用一個資料來源的事務管理器了。那麼對於一個方法涉及到多個資料來源操作需要保證事務一致性的怎麼辦呢?

實現跨資料來源事務

基於註解+AOP使用程式設計式事務的方式實現跨資料來源事務

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MultiDataSourceTransactional {
    /**
     * 事務管理器陣列
     */
    String[] transactionManagers();
}

首先多個資料來源的事務分別都開起來,然後各事務分別去執行對應的sql(此所謂第一階段提交),最後如果都成功就把事務全部提交,只要有一個失敗就把事務都回滾——此所謂第二階段提交。

/**
 * 需要注意的點:
 * 1)宣告事務和提交事務或者回滾事務的順序應該相反的,就是先進後出,所以採用了棧來儲存。
 * 2)執行緒執行結束後記得清空本地變數。
 * 3)可以參照@Transactional的那些屬性升級功能,比如隔離級別回滾異常等。
 */
@Component
@Aspect
public class MultiTransactionAop {
    /**
     * 執行緒本地變數:為什麼使用棧?※為了達到後進先出的效果※
     */
    private static final ThreadLocal<Stack<Map<DataSourceTransactionManager, TransactionStatus>>> THREAD_LOCAL = new ThreadLocal<>();
    private static Logger logger = LoggerFactory.getLogger(MultiTransactionAop.class);
    /**
     * 用於獲取事務管理器
     */
    @Autowired
    private ApplicationContext applicationContext;
    /**
     * 事務宣告
     */
    private DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    {
        // 非唯讀模式
        def.setReadOnly(false);
        // 事務隔離級別:採用資料庫的
        def.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
        // 事務傳播行為
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    }
    /**
     * 切點
     */
    @Pointcut("@annotation(cn.zysheep.datasource.anntation.MultiDataSourceTransactional)")
    public void pointcut() {
    }
    /**
     * 宣告事務
     *
     * @param transactional 註解
     */
    @Before("pointcut() && @annotation(transactional)")
    public void before(MultiDataSourceTransactional transactional) {
        // 根據設定的事務名稱按順序宣告,並放到ThreadLocal裡
        String[] transactionManagerNames = transactional.transactionManagers();
        Stack<Map<DataSourceTransactionManager, TransactionStatus>> pairStack = new Stack<>();
        for (String transactionManagerName : transactionManagerNames) {
            DataSourceTransactionManager transactionManager = applicationContext.getBean(transactionManagerName, DataSourceTransactionManager.class);
            TransactionStatus transactionStatus = transactionManager.getTransaction(def);
            Map<DataSourceTransactionManager, TransactionStatus> transactionMap = new HashMap<>();
            transactionMap.put(transactionManager, transactionStatus);
            pairStack.push(transactionMap);
        }
        THREAD_LOCAL.set(pairStack);
    }
    /**
     * 後置增強,相當於AfterReturningAdvice,方法退出時執行
     *
     * 提交事務
     */
    @AfterReturning("pointcut()")
    public void afterReturning() {
        // ※棧頂彈出(後進先出)
        Stack<Map<DataSourceTransactionManager, TransactionStatus>> pairStack = THREAD_LOCAL.get();
        while (!pairStack.empty()) {
            Map<DataSourceTransactionManager, TransactionStatus> pair = pairStack.pop();
            pair.forEach((key,value)->key.commit(value));
        }
        THREAD_LOCAL.remove();
    }
    /**
     * 異常丟擲增強,相當於ThrowsAdvice
     *
     * 回滾事務
     */
    @AfterThrowing(value = "pointcut()")
    public void afterThrowing() {
        // ※棧頂彈出(後進先出)
        Stack<Map<DataSourceTransactionManager, TransactionStatus>> pairStack = THREAD_LOCAL.get();
        logger.info("=========================");
        logger.info("Pair Stack:{}", pairStack);
        logger.info("=========================");
        while (!pairStack.empty()) {
            Map<DataSourceTransactionManager, TransactionStatus> pair = pairStack.pop();
            pair.forEach((key,value)->key.rollback(value));
        }
        THREAD_LOCAL.remove();
    }
}

在事務的方法上新增前面我們的多資料來源事務註解

 /**
     * 測試多資料來源事務
     */
    @MultiDataSourceTransactional(transactionManagers = {"masterTransactionManager", "clusterTransactionManager"})
    @Override
    public void saveUser() {
        String rid = UUID.randomUUID().toString();
        User user = new User();
        user.setId(rid);
        userMapper.saveUser(user);
        Log log = new Log();
        log.setId(rid);
        logMapper.saveLog(log);
        throw new RuntimeException();
    }

到此這篇關於SpringBoot整合Mybatis實現多資料來源設定與跨資料來源事務範例的文章就介紹到這了,更多相關SpringBoot多資料來源設定內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com