当前位置: 首页 > news >正文

莱芜都市网二手直通车关键词怎么优化

莱芜都市网二手,直通车关键词怎么优化,做橙光游戏的网站,网络规划设计师可以同时报名吗Spring如何在多线程下保持事务的一致性 方法:每个线程都开启各自的事务去执行相关业务,等待所有线程的业务执行完成,统一提交或回滚。 下面我们通过具体的案例来演示Spring如何在多线程下保持事务的一致性。 1、项目结构 2、数据库SQL CR…

Spring如何在多线程下保持事务的一致性

方法:每个线程都开启各自的事务去执行相关业务,等待所有线程的业务执行完成,统一提交或回滚。

下面我们通过具体的案例来演示Spring如何在多线程下保持事务的一致性。

1、项目结构

在这里插入图片描述

2、数据库SQL

CREATE TABLE `student` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) NOT NULL DEFAULT '',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

3、pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.6</version><relativePath/></parent><groupId>com.example</groupId><artifactId>Transaction</artifactId><version>0.0.1-SNAPSHOT</version><name>Transaction</name><description>Transaction</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

4、配置文件

spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

5、实体类

package com.example.transaction.model;import java.io.Serializable;/*** @author tom*/
public class Student implements Serializable {private static final long serialVersionUID = 1L;private int id;private String name;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Student(String name) {this.name = name;}
}

6、Mapper

package com.example.transaction.mapper;import com.example.transaction.model.Student;
import org.apache.ibatis.annotations.Insert;
import org.springframework.stereotype.Component;/*** @author tom*/
@Component
public interface StudentMapper {/*** 插入student* @param student*/@Insert("insert into student(name) VALUES(#{name})")void insert(Student student);
}

7、数据源配置

package com.example.transaction.config;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;/*** @author tom*/
@Configuration
@MapperScan(basePackages = "com.example.transaction.mapper")
public class DataSourceConfig {@ConfigurationProperties(prefix = "spring.datasource")@Beanpublic DataSource getDataSource() {return DataSourceBuilder.create().build();}@Beanpublic DataSourceTransactionManager getTransactionManager(DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}}

8、测试

package com.example.transaction;import com.example.transaction.mapper.StudentMapper;
import com.example.transaction.model.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class TransactionApplicationTests {@Autowiredprivate StudentMapper studentMapper;@Testvoid contextLoads() {studentMapper.insert(new Student("John"));}}

我们先进行测试,看数据库是否可以正常插入,执行完的结果:

idname
1John

9、线程池

package com.example.transaction.config;import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;/*** @author tom*/
public class ExecutorConfig {private final static int MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors();private final static int QUEUE_SIZE = 500;private volatile static ExecutorService executorService;public static ExecutorService getThreadPool() {if (executorService == null) {synchronized (ExecutorConfig.class) {if (executorService == null) {executorService = newThreadPool();}}}return executorService;}private static ExecutorService newThreadPool() {int corePool = Math.min(5, MAX_POOL_SIZE);return new ThreadPoolExecutor(corePool, MAX_POOL_SIZE, 10000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(QUEUE_SIZE), new ThreadPoolExecutor.AbortPolicy());}private ExecutorConfig() {}
}

10、多线程事务管理

package com.example.transaction.service;import com.example.transaction.config.ExecutorConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;/*** @author tom*/
@Service
public class MultiThreadingTransactionManager {/*** 数据源事务管理器*/private DataSourceTransactionManager dataSourceTransactionManager;@Autowiredpublic void setUserService(DataSourceTransactionManager dataSourceTransactionManager) {this.dataSourceTransactionManager = dataSourceTransactionManager;}/*** 用于判断子线程业务是否处理完成* 处理完成时threadCountDownLatch的值为0*/private CountDownLatch threadCountDownLatch;/*** 用于等待子线程全部完成后,子线程统一进行提交和回滚* 进行提交和回滚时mainCountDownLatch的值为0*/private final CountDownLatch mainCountDownLatch = new CountDownLatch(1);/*** 是否提交事务,默认是true,当子线程有异常发生时,设置为false,回滚事务*/private final AtomicBoolean isSubmit = new AtomicBoolean(true);public boolean execute(List<Runnable> runnableList) {// 超时时间long timeout = 30;setThreadCountDownLatch(runnableList.size());ExecutorService executorService = ExecutorConfig.getThreadPool();runnableList.forEach(runnable -> executorService.execute(() -> executeThread(runnable, threadCountDownLatch, mainCountDownLatch, isSubmit)));// 等待子线程全部执行完毕try {// 若计数器变为零了,则返回 trueboolean isFinish = threadCountDownLatch.await(timeout, TimeUnit.SECONDS);if (!isFinish) {// 如果还有为执行完成的就回滚isSubmit.set(false);System.out.println("存在子线程在预期时间内未执行完毕,任务将全部回滚");}} catch (Exception exception) {System.out.println("主线程发生异常,异常为: " + exception.getMessage());} finally {// 计数器减1,代表该主线程执行完毕mainCountDownLatch.countDown();}// 返回结果,是否执行成功,事务提交即为执行成功,事务回滚即为执行失败return isSubmit.get();}private void executeThread(Runnable runnable, CountDownLatch threadCountDownLatch, CountDownLatch mainCountDownLatch, AtomicBoolean isSubmit) {System.out.println("子线程: [" + Thread.currentThread().getName() + "]");// 判断别的子线程是否已经出现错误,错误别的线程已经出现错误,那么所有的都要回滚,这个子线程就没有必要执行了if (!isSubmit.get()) {System.out.println("整个事务中有子线程执行失败需要回滚, 子线程: [" + Thread.currentThread().getName() + "] 终止执行");// 计数器减1,代表该子线程执行完毕threadCountDownLatch.countDown();return;}// 开启事务DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(defaultTransactionDefinition);try {// 执行业务逻辑runnable.run();} catch (Exception exception) {// 发生异常需要进行回滚,设置isSubmit为falseisSubmit.set(false);System.out.println("子线程: [" + Thread.currentThread().getName() + "]执行业务发生异常,异常为: " + exception.getMessage());} finally {// 计数器减1,代表该子线程执行完毕threadCountDownLatch.countDown();}try {// 等待主线程执行mainCountDownLatch.await();} catch (Exception exception) {System.out.println("子线程: [" + Thread.currentThread().getName() + "]等待提交或回滚异常,异常为: " + exception.getMessage());}try {// 提交if (isSubmit.get()) {dataSourceTransactionManager.commit(transactionStatus);System.out.println("子线程: [" + Thread.currentThread().getName() + "]进行事务提交");} else {dataSourceTransactionManager.rollback(transactionStatus);System.out.println("子线程: [" + Thread.currentThread().getName() + "]进行事务回滚");}} catch (Exception exception) {System.out.println("子线程: [" + Thread.currentThread().getName() + "]进行事务提交或回滚出现异常,异常为:" + exception.getMessage());}}private void setThreadCountDownLatch(int num) {this.threadCountDownLatch = new CountDownLatch(num);}}

11、正常插入

package com.example.transaction;import com.example.transaction.mapper.StudentMapper;
import com.example.transaction.model.Student;
import com.example.transaction.service.MultiThreadingTransactionManager;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;
import java.util.List;@SpringBootTest
public class TransactionApplicationTwoTests {@Autowiredprivate StudentMapper studentMapper;@Autowiredprivate MultiThreadingTransactionManager multiThreadingTransactionManager;@Testvoid contextLoads() {List<Student> studentList = new ArrayList<>();studentList.add(new Student("tom"));studentList.add(new Student("marry"));List<Runnable> runnableList = new ArrayList<>();studentList.forEach(student -> runnableList.add(() -> {System.out.println("当前线程:[" + Thread.currentThread().getName() + "] 插入数据: " + student);try {studentMapper.insert(student);} catch (Exception e) {e.printStackTrace();}}));boolean isSuccess = multiThreadingTransactionManager.execute(runnableList);System.out.println(isSuccess);}
}

日志输出:

......
子线程: [pool-1-thread-2]
子线程: [pool-1-thread-1]
2023-11-26 17:15:42.138  INFO 15736 --- [pool-1-thread-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-11-26 17:15:42.319  INFO 15736 --- [pool-1-thread-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
当前线程:[pool-1-thread-2] 插入数据: com.example.transaction.model.Student@1f52ee45
当前线程:[pool-1-thread-1] 插入数据: com.example.transaction.model.Student@238acf6d
true
子线程: [pool-1-thread-2]进行事务提交
子线程: [pool-1-thread-1]进行事务提交

数据库中的数据:

idname
1John
2tom
3marry

12、异常插入

package com.example.transaction;import com.example.transaction.mapper.StudentMapper;
import com.example.transaction.model.Student;
import com.example.transaction.service.MultiThreadingTransactionManager;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;
import java.util.List;@SpringBootTest
public class TransactionApplicationThreeTests {@Autowiredprivate StudentMapper studentMapper;@Autowiredprivate MultiThreadingTransactionManager multiThreadingTransactionManager;@Testvoid contextLoads() {List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三"));studentList.add(new Student("李四"));List<Runnable> runnableList = new ArrayList<>();studentList.forEach(student -> runnableList.add(() -> {System.out.println("当前线程:[" + Thread.currentThread().getName() + "] 插入数据: " + student);try {studentMapper.insert(student);} catch (Exception e) {e.printStackTrace();}}));runnableList.add(() -> System.out.println(1 / 0));boolean isSuccess = multiThreadingTransactionManager.execute(runnableList);System.out.println(isSuccess);}
}

日志输出:

......
子线程: [pool-1-thread-1]
子线程: [pool-1-thread-2]
子线程: [pool-1-thread-3]
2023-11-26 17:19:45.876  INFO 11384 --- [pool-1-thread-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-11-26 17:19:46.034  INFO 11384 --- [pool-1-thread-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
子线程: [pool-1-thread-3]执行业务发生异常,异常为: / by zero
当前线程:[pool-1-thread-1] 插入数据: com.example.transaction.model.Student@6231e93c
当前线程:[pool-1-thread-2] 插入数据: com.example.transaction.model.Student@74568de7
false
子线程: [pool-1-thread-3]进行事务回滚
子线程: [pool-1-thread-2]进行事务回滚

数据库中的数据:

idname
1John
2tom
3marry

从上面我们可以看出事务进行了回滚,并没有插入到数据库中。

13、在主线程中统一进行事务的提交和回滚

这里将事务的回滚放在所有子线程执行完毕之后。

package com.example.transaction.service;import com.example.transaction.config.ExecutorConfig;
import lombok.Builder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;import javax.sql.DataSource;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;/*** @author tom*/
@Service
public class MultiThreadingTransactionManagerTwo {/*** 数据源事务管理器*/private DataSourceTransactionManager dataSourceTransactionManager;@Autowiredpublic void setUserService(DataSourceTransactionManager dataSourceTransactionManager) {this.dataSourceTransactionManager = dataSourceTransactionManager;}/*** 用于判断子线程业务是否处理完成* 处理完成时threadCountDownLatch的值为0*/private CountDownLatch threadCountDownLatch;/*** 是否提交事务,默认是true,当子线程有异常发生时,设置为false,回滚事务*/private final AtomicBoolean isSubmit = new AtomicBoolean(true);public boolean execute(List<Runnable> runnableList) {// 超时时间long timeout = 30;List<TransactionStatus> transactionStatusList = Collections.synchronizedList(new ArrayList<>());List<TransactionResource> transactionResourceList = Collections.synchronizedList(new ArrayList<>());setThreadCountDownLatch(runnableList.size());ExecutorService executorService = ExecutorConfig.getThreadPool();runnableList.forEach(runnable -> executorService.execute(() -> {try {// 执行业务逻辑executeThread(runnable, transactionStatusList, transactionResourceList);} catch (Exception exception) {exception.printStackTrace();// 执行异常,需要回滚isSubmit.set(false);} finally {threadCountDownLatch.countDown();}}));// 等待子线程全部执行完毕try {// 若计数器变为零了,则返回 trueboolean isFinish = threadCountDownLatch.await(timeout, TimeUnit.SECONDS);if (!isFinish) {// 如果还有为执行完成的就回滚isSubmit.set(false);System.out.println("存在子线程在预期时间内未执行完毕,任务将全部回滚");}} catch (Exception exception) {exception.printStackTrace();}// 发生了异常则进行回滚操作,否则提交if (isSubmit.get()) {System.out.println("全部事务正常提交");for (int i = 0; i < runnableList.size(); i++) {transactionResourceList.get(i).autoWiredTransactionResource();dataSourceTransactionManager.commit(transactionStatusList.get(i));transactionResourceList.get(i).removeTransactionResource();}} else {System.out.println("发生异常,全部事务回滚");for (int i = 0; i < runnableList.size(); i++) {transactionResourceList.get(i).autoWiredTransactionResource();dataSourceTransactionManager.rollback(transactionStatusList.get(i));transactionResourceList.get(i).removeTransactionResource();}}// 返回结果,是否执行成功,事务提交即为执行成功,事务回滚即为执行失败return isSubmit.get();}private void executeThread(Runnable runnable, List<TransactionStatus> transactionStatusList, List<TransactionResource> transactionResourceList) {System.out.println("子线程: [" + Thread.currentThread().getName() + "]");DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(defaultTransactionDefinition);// 开启新事务transactionStatusList.add(transactionStatus);// copy事务资源transactionResourceList.add(TransactionResource.copyTransactionResource());// 执行业务逻辑runnable.run();}private void setThreadCountDownLatch(int num) {this.threadCountDownLatch = new CountDownLatch(num);}/*** 保存当前事务资源,用于线程间的事务资源COPY操作* <p>* `@Builder`注解是Lombok库提供的一个注解,它可以用于自动生成Builder模式的代码,使用@Builder注解可以简化创建对象实例的过程,并且可以使代码更加清晰和易于维护*/@Builderprivate static class TransactionResource {// TransactionSynchronizationManager类内部默认提供了下面六个ThreadLocal属性,分别保存当前线程对应的不同事务资源// 保存当前事务关联的资源,默认只会在新建事务的时候保存当前获取到的DataSource和当前事务对应Connection的映射关系// 当然这里Connection被包装为了ConnectionHolder// 事务结束后默认会移除集合中的DataSource作为key关联的资源记录private Map<Object, Object> resources;//下面五个属性会在事务结束后被自动清理,无需我们手动清理// 事务监听者,在事务执行到某个阶段的过程中,会去回调监听者对应的回调接口(典型观察者模式的应用),默认为空集合private Set<TransactionSynchronization> synchronizations;// 存放当前事务名字private String currentTransactionName;// 存放当前事务是否是只读事务private Boolean currentTransactionReadOnly;// 存放当前事务的隔离级别private Integer currentTransactionIsolationLevel;// 存放当前事务是否处于激活状态private Boolean actualTransactionActive;/*** 对事务资源进行复制** @return TransactionResource*/public static TransactionResource copyTransactionResource() {return TransactionResource.builder()//返回的是不可变集合.resources(TransactionSynchronizationManager.getResourceMap())//如果需要注册事务监听者,这里记得修改,我们这里不需要,就采用默认负责,spring事务内部默认也是这个值.synchronizations(new LinkedHashSet<>()).currentTransactionName(TransactionSynchronizationManager.getCurrentTransactionName()).currentTransactionReadOnly(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).currentTransactionIsolationLevel(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()).actualTransactionActive(TransactionSynchronizationManager.isActualTransactionActive()).build();}/*** 使用*/public void autoWiredTransactionResource() {resources.forEach(TransactionSynchronizationManager::bindResource);//如果需要注册事务监听者,这里记得修改,我们这里不需要,就采用默认负责,spring事务内部默认也是这个值TransactionSynchronizationManager.initSynchronization();TransactionSynchronizationManager.setActualTransactionActive(actualTransactionActive);TransactionSynchronizationManager.setCurrentTransactionName(currentTransactionName);TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(currentTransactionIsolationLevel);TransactionSynchronizationManager.setCurrentTransactionReadOnly(currentTransactionReadOnly);}/*** 移除*/public void removeTransactionResource() {// 事务结束后默认会移除集合中的DataSource作为key关联的资源记录// DataSource如果重复移除,unbindResource时会因为不存在此key关联的事务资源而报错resources.keySet().forEach(key -> {if (!(key instanceof DataSource)) {TransactionSynchronizationManager.unbindResource(key);}});}}
}

13.1 正常插入

package com.example.transaction;import com.example.transaction.mapper.StudentMapper;
import com.example.transaction.model.Student;
import com.example.transaction.service.MultiThreadingTransactionManagerTwo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;
import java.util.List;@SpringBootTest
public class TransactionApplicationFourTests {@Autowiredprivate StudentMapper studentMapper;@Autowiredprivate MultiThreadingTransactionManagerTwo multiThreadingTransactionManagerTwo;@Testvoid contextLoads() {List<Student> studentList = new ArrayList<>();studentList.add(new Student("tom"));studentList.add(new Student("marry"));List<Runnable> runnableList = new ArrayList<>();studentList.forEach(student -> runnableList.add(() -> {System.out.println("当前线程:[" + Thread.currentThread().getName() + "] 插入数据: " + student);try {studentMapper.insert(student);} catch (Exception e) {e.printStackTrace();}}));boolean isSuccess = multiThreadingTransactionManagerTwo.execute(runnableList);System.out.println(isSuccess);}
}

日志输出:

......
子线程: [pool-1-thread-1]
子线程: [pool-1-thread-2]
2023-11-26 18:57:13.096  INFO 4280 --- [pool-1-thread-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-11-26 18:57:13.256  INFO 4280 --- [pool-1-thread-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
当前线程:[pool-1-thread-2] 插入数据: com.example.transaction.model.Student@6cf36c13
当前线程:[pool-1-thread-1] 插入数据: com.example.transaction.model.Student@7fc3efd5
全部事务正常提交
true

数据库中的数据:

idname
1John
2tom
3marry
6tom
7marry

13.2 异常插入

package com.example.transaction;import com.example.transaction.mapper.StudentMapper;
import com.example.transaction.model.Student;
import com.example.transaction.service.MultiThreadingTransactionManager;
import com.example.transaction.service.MultiThreadingTransactionManagerTwo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;
import java.util.List;@SpringBootTest
public class TransactionApplicationFiveTests {@Autowiredprivate StudentMapper studentMapper;@Autowiredprivate MultiThreadingTransactionManagerTwo multiThreadingTransactionManagerTwo;@Testvoid contextLoads() {List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三"));studentList.add(new Student("李四"));List<Runnable> runnableList = new ArrayList<>();studentList.forEach(student -> runnableList.add(() -> {System.out.println("当前线程:[" + Thread.currentThread().getName() + "] 插入数据: " + student);try {studentMapper.insert(student);} catch (Exception e) {e.printStackTrace();}}));runnableList.add(() -> System.out.println(1 / 0));boolean isSuccess = multiThreadingTransactionManagerTwo.execute(runnableList);System.out.println(isSuccess);}
}

日志输出:

子线程: [pool-1-thread-1]
子线程: [pool-1-thread-3]
子线程: [pool-1-thread-2]
2023-11-26 19:00:40.938  INFO 17920 --- [pool-1-thread-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-11-26 19:00:41.097  INFO 17920 --- [pool-1-thread-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
当前线程:[pool-1-thread-1] 插入数据: com.example.transaction.model.Student@2f7e458
当前线程:[pool-1-thread-2] 插入数据: com.example.transaction.model.Student@2b3ae8b
java.lang.ArithmeticException: / by zeroat com.example.transaction.TransactionApplicationFiveTests.lambda$contextLoads$2(TransactionApplicationFiveTests.java:37)at com.example.transaction.service.MultiThreadingTransactionManagerTwo.executeThread(MultiThreadingTransactionManagerTwo.java:107)at com.example.transaction.service.MultiThreadingTransactionManagerTwo.lambda$null$0(MultiThreadingTransactionManagerTwo.java:57)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)at java.lang.Thread.run(Thread.java:745)
发生异常,全部事务回滚
false

数据库中的数据:

idname
1John
2tom
3marry
6tom
7marry

14、使用CompletableFuture实现

package com.example.transaction.service;import lombok.Builder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;import javax.sql.DataSource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;/*** @author tom*/
@Service
public class MultiThreadingTransactionManagerThree {/*** 数据源事务管理器*/private DataSourceTransactionManager dataSourceTransactionManager;@Autowiredpublic void setUserService(DataSourceTransactionManager dataSourceTransactionManager) {this.dataSourceTransactionManager = dataSourceTransactionManager;}/*** 是否提交事务,默认是true,当子线程有异常发生时,设置为false,回滚事务*/private final AtomicBoolean isSubmit = new AtomicBoolean(true);public boolean execute(List<Runnable> runnableList) {List<TransactionStatus> transactionStatusList = Collections.synchronizedList(new ArrayList<>());List<TransactionResource> transactionResourceList = Collections.synchronizedList(new ArrayList<>());List<CompletableFuture<?>> completableFutureList = new ArrayList<>(runnableList.size());runnableList.forEach(runnable -> completableFutureList.add(CompletableFuture.runAsync(() -> {try {// 执行业务逻辑executeThread(runnable, transactionStatusList, transactionResourceList);} catch (Exception exception) {exception.printStackTrace();// 执行异常,需要回滚isSubmit.set(false);// 终止其它还未执行的任务completableFutureList.forEach(completableFuture -> completableFuture.cancel(true));}})));// 等待子线程全部执行完毕try {// 阻塞直到所有任务全部执行结束,如果有任务被取消,这里会抛出异常,需要捕获CompletableFuture.allOf(completableFutureList.toArray(new CompletableFuture[]{})).get();} catch (Exception exception) {exception.printStackTrace();}// 发生了异常则进行回滚操作,否则提交if (!isSubmit.get()) {System.out.println("发生异常,全部事务回滚");for (int i = 0; i < runnableList.size(); i++) {transactionResourceList.get(i).autoWiredTransactionResource();dataSourceTransactionManager.rollback(transactionStatusList.get(i));transactionResourceList.get(i).removeTransactionResource();}} else {System.out.println("全部事务正常提交");for (int i = 0; i < runnableList.size(); i++) {transactionResourceList.get(i).autoWiredTransactionResource();dataSourceTransactionManager.commit(transactionStatusList.get(i));transactionResourceList.get(i).removeTransactionResource();}}// 返回结果,是否执行成功,事务提交即为执行成功,事务回滚即为执行失败return isSubmit.get();}private void executeThread(Runnable runnable, List<TransactionStatus> transactionStatusList, List<TransactionResource> transactionResourceList) {System.out.println("子线程: [" + Thread.currentThread().getName() + "]");DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(defaultTransactionDefinition);// 开启新事务transactionStatusList.add(transactionStatus);// copy事务资源transactionResourceList.add(TransactionResource.copyTransactionResource());// 执行业务逻辑runnable.run();}/*** 保存当前事务资源,用于线程间的事务资源COPY操作* <p>* `@Builder`注解是Lombok库提供的一个注解,它可以用于自动生成Builder模式的代码,使用@Builder注解可以简化创建对象实例的过程,并且可以使代码更加清晰和易于维护*/@Builderprivate static class TransactionResource {// TransactionSynchronizationManager类内部默认提供了下面六个ThreadLocal属性,分别保存当前线程对应的不同事务资源// 保存当前事务关联的资源,默认只会在新建事务的时候保存当前获取到的DataSource和当前事务对应Connection的映射关系// 当然这里Connection被包装为了ConnectionHolder// 事务结束后默认会移除集合中的DataSource作为key关联的资源记录private Map<Object, Object> resources;//下面五个属性会在事务结束后被自动清理,无需我们手动清理// 事务监听者,在事务执行到某个阶段的过程中,会去回调监听者对应的回调接口(典型观察者模式的应用),默认为空集合private Set<TransactionSynchronization> synchronizations;// 存放当前事务名字private String currentTransactionName;// 存放当前事务是否是只读事务private Boolean currentTransactionReadOnly;// 存放当前事务的隔离级别private Integer currentTransactionIsolationLevel;// 存放当前事务是否处于激活状态private Boolean actualTransactionActive;/*** 对事务资源进行复制** @return TransactionResource*/public static TransactionResource copyTransactionResource() {return TransactionResource.builder()//返回的是不可变集合.resources(TransactionSynchronizationManager.getResourceMap())//如果需要注册事务监听者,这里记得修改,我们这里不需要,就采用默认负责,spring事务内部默认也是这个值.synchronizations(new LinkedHashSet<>()).currentTransactionName(TransactionSynchronizationManager.getCurrentTransactionName()).currentTransactionReadOnly(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).currentTransactionIsolationLevel(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()).actualTransactionActive(TransactionSynchronizationManager.isActualTransactionActive()).build();}/*** 使用*/public void autoWiredTransactionResource() {resources.forEach(TransactionSynchronizationManager::bindResource);//如果需要注册事务监听者,这里记得修改,我们这里不需要,就采用默认负责,spring事务内部默认也是这个值TransactionSynchronizationManager.initSynchronization();TransactionSynchronizationManager.setActualTransactionActive(actualTransactionActive);TransactionSynchronizationManager.setCurrentTransactionName(currentTransactionName);TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(currentTransactionIsolationLevel);TransactionSynchronizationManager.setCurrentTransactionReadOnly(currentTransactionReadOnly);}/*** 移除*/public void removeTransactionResource() {// 事务结束后默认会移除集合中的DataSource作为key关联的资源记录// DataSource如果重复移除,unbindResource时会因为不存在此key关联的事务资源而报错resources.keySet().forEach(key -> {if (!(key instanceof DataSource)) {TransactionSynchronizationManager.unbindResource(key);}});}}
}

14.1 正常插入

package com.example.transaction;import com.example.transaction.mapper.StudentMapper;
import com.example.transaction.model.Student;
import com.example.transaction.service.MultiThreadingTransactionManagerThree;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;
import java.util.List;@SpringBootTest
public class TransactionApplicationSixTests {@Autowiredprivate StudentMapper studentMapper;@Autowiredprivate MultiThreadingTransactionManagerThree multiThreadingTransactionManagerThree;@Testvoid contextLoads() {List<Student> studentList = new ArrayList<>();studentList.add(new Student("tom"));studentList.add(new Student("marry"));List<Runnable> runnableList = new ArrayList<>();studentList.forEach(student -> runnableList.add(() -> {System.out.println("当前线程:[" + Thread.currentThread().getName() + "] 插入数据: " + student);try {studentMapper.insert(student);} catch (Exception e) {e.printStackTrace();}}));boolean isSuccess = multiThreadingTransactionManagerThree.execute(runnableList);System.out.println(isSuccess);}
}

日志输出:

子线程: [ForkJoinPool.commonPool-worker-1]
子线程: [ForkJoinPool.commonPool-worker-2]
2023-11-26 19:17:00.674  INFO 12344 --- [onPool-worker-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-11-26 19:17:00.815  INFO 12344 --- [onPool-worker-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
当前线程:[ForkJoinPool.commonPool-worker-2] 插入数据: com.example.transaction.model.Student@25e1950b
当前线程:[ForkJoinPool.commonPool-worker-1] 插入数据: com.example.transaction.model.Student@57e8ff9a
全部事务正常提交
true

数据库中的数据:

idname
1John
2tom
3marry
6tom
7marry
10tom
11marry

14.2 异常插入

package com.example.transaction;import com.example.transaction.mapper.StudentMapper;
import com.example.transaction.model.Student;
import com.example.transaction.service.MultiThreadingTransactionManagerThree;
import com.example.transaction.service.MultiThreadingTransactionManagerTwo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;
import java.util.List;@SpringBootTest
public class TransactionApplicationSevenTests {@Autowiredprivate StudentMapper studentMapper;@Autowiredprivate MultiThreadingTransactionManagerThree multiThreadingTransactionManagerThree;@Testvoid contextLoads() {List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三"));studentList.add(new Student("李四"));List<Runnable> runnableList = new ArrayList<>();studentList.forEach(student -> runnableList.add(() -> {System.out.println("当前线程:[" + Thread.currentThread().getName() + "] 插入数据: " + student);try {studentMapper.insert(student);} catch (Exception e) {e.printStackTrace();}}));runnableList.add(() -> System.out.println(1 / 0));boolean isSuccess = multiThreadingTransactionManagerThree.execute(runnableList);System.out.println(isSuccess);}
}

输出日志:

子线程: [ForkJoinPool.commonPool-worker-2]
子线程: [ForkJoinPool.commonPool-worker-3]
子线程: [ForkJoinPool.commonPool-worker-1]
2023-11-26 19:19:01.862  INFO 15120 --- [onPool-worker-3] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-11-26 19:19:02.016  INFO 15120 --- [onPool-worker-3] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
当前线程:[ForkJoinPool.commonPool-worker-1] 插入数据: com.example.transaction.model.Student@3155d2ee
当前线程:[ForkJoinPool.commonPool-worker-2] 插入数据: com.example.transaction.model.Student@5ff9bde5
java.lang.ArithmeticException: / by zeroat com.example.transaction.TransactionApplicationSevenTests.lambda$contextLoads$2(TransactionApplicationSevenTests.java:37)at com.example.transaction.service.MultiThreadingTransactionManagerThree.executeThread(MultiThreadingTransactionManagerThree.java:90)at com.example.transaction.service.MultiThreadingTransactionManagerThree.lambda$null$1(MultiThreadingTransactionManagerThree.java:45)at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1626)at java.util.concurrent.CompletableFuture$AsyncRun.exec(CompletableFuture.java:1618)at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
java.util.concurrent.ExecutionException: java.util.concurrent.CancellationExceptionat java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895)
......
com.example.transaction.service.MultiThreadingTransactionManagerThree.lambda$null$1(MultiThreadingTransactionManagerThree.java:51)at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1626)at java.util.concurrent.CompletableFuture$AsyncRun.exec(CompletableFuture.java:1618)at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
发生异常,全部事务回滚
false

数据库中的数据:

idname
1John
2tom
3marry
6tom
7marry
10tom
11marry

至此,结束。


文章转载自:
http://forge.wgkz.cn
http://lasya.wgkz.cn
http://miri.wgkz.cn
http://bookstand.wgkz.cn
http://bangkok.wgkz.cn
http://precative.wgkz.cn
http://hackney.wgkz.cn
http://tarriance.wgkz.cn
http://basan.wgkz.cn
http://unbalance.wgkz.cn
http://untearable.wgkz.cn
http://outermost.wgkz.cn
http://cancelation.wgkz.cn
http://zoogeny.wgkz.cn
http://outlearn.wgkz.cn
http://imagine.wgkz.cn
http://seadog.wgkz.cn
http://aerial.wgkz.cn
http://liveable.wgkz.cn
http://cupper.wgkz.cn
http://physical.wgkz.cn
http://airless.wgkz.cn
http://calculatedly.wgkz.cn
http://undignified.wgkz.cn
http://dies.wgkz.cn
http://comdex.wgkz.cn
http://anaerobium.wgkz.cn
http://blinker.wgkz.cn
http://brawler.wgkz.cn
http://remerge.wgkz.cn
http://inflammation.wgkz.cn
http://inquiline.wgkz.cn
http://lopsided.wgkz.cn
http://doddery.wgkz.cn
http://licity.wgkz.cn
http://tugboatman.wgkz.cn
http://workpeople.wgkz.cn
http://waterflood.wgkz.cn
http://cacophonize.wgkz.cn
http://prescientific.wgkz.cn
http://playstation.wgkz.cn
http://encephalasthenia.wgkz.cn
http://petechial.wgkz.cn
http://koradji.wgkz.cn
http://grovy.wgkz.cn
http://amygdalotomy.wgkz.cn
http://philogyny.wgkz.cn
http://windrow.wgkz.cn
http://nccl.wgkz.cn
http://hepatotoxin.wgkz.cn
http://eruptive.wgkz.cn
http://demonstration.wgkz.cn
http://conspue.wgkz.cn
http://monolog.wgkz.cn
http://ordnance.wgkz.cn
http://bag.wgkz.cn
http://wording.wgkz.cn
http://elective.wgkz.cn
http://episcopalian.wgkz.cn
http://napper.wgkz.cn
http://playmate.wgkz.cn
http://lps.wgkz.cn
http://pristane.wgkz.cn
http://afterglow.wgkz.cn
http://lincolnesque.wgkz.cn
http://fargoing.wgkz.cn
http://ethicals.wgkz.cn
http://eftpos.wgkz.cn
http://allotype.wgkz.cn
http://fluidonics.wgkz.cn
http://exertion.wgkz.cn
http://monospermal.wgkz.cn
http://reperusal.wgkz.cn
http://styptical.wgkz.cn
http://whiten.wgkz.cn
http://senescent.wgkz.cn
http://cordwainer.wgkz.cn
http://emulous.wgkz.cn
http://lefty.wgkz.cn
http://skinniness.wgkz.cn
http://kainogenesis.wgkz.cn
http://alfine.wgkz.cn
http://taxonomic.wgkz.cn
http://bouilli.wgkz.cn
http://thorite.wgkz.cn
http://clastic.wgkz.cn
http://neurospora.wgkz.cn
http://flybelt.wgkz.cn
http://laird.wgkz.cn
http://urochordate.wgkz.cn
http://dentex.wgkz.cn
http://returf.wgkz.cn
http://bidialectism.wgkz.cn
http://chiack.wgkz.cn
http://inmost.wgkz.cn
http://cazique.wgkz.cn
http://vestibulectomy.wgkz.cn
http://polydymite.wgkz.cn
http://uncharity.wgkz.cn
http://expansionary.wgkz.cn
http://www.dt0577.cn/news/60767.html

相关文章:

  • 那里可以做app网站沈阳百度推广优化
  • b2c平台有免费seo教程
  • 有趣的编程代码上海外贸网站seo
  • 中国十大企业排名2021seo网络搜索引擎优化
  • 嘉兴网站模板建站湖南好搜公司seo
  • 网站建设灬金手指下拉十五今天的新闻大事10条
  • 什么网站做网页好网站建设流程是什么
  • 郑州网站设计 郑州网站开发武汉百度快速排名提升
  • 太原h5建站考证培训机构报名网站
  • 如何做网站页面赚钱一站式网站建设公司
  • 网站开发的需求分析论文培训报名
  • 网站开发 明细万网域名注册官网查询
  • 网页排版设计软件重庆seo服务
  • 不动产登记门户网站建设怎么在网上推广产品
  • 打开网站要密码黑五类广告推广
  • 做搜狗网站点击商丘网络推广公司
  • 蓝色网站建设国外黄冈网站推广软件
  • 微信网站制作方案seo在线网站推广
  • 网站开发费用报价表百度百度seo优
  • 如何做旅游网站国内销售平台有哪些
  • 公司网站找谁做朝阳seo排名优化培训
  • 给企业做网站大数据营销是什么
  • 景洪服装网站建设今日国际重大新闻
  • wordpress文章url设置seo优化软件
  • 北滘网站建设企业网络推广技巧
  • 怎么做仿制网站网站建设的推广渠道
  • 布吉做棋牌网站建设哪家便宜长沙疫情最新数据消息
  • 怎么设置自己做的网站网站关键词全国各地的排名情况
  • 南昌vr网站开发淘宝引流推广平台
  • 网络优化师自学网站温州seo