亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java多線程事務(wù)回滾@Transactional失效處理方案

 更新時間:2022年08月09日 14:12:51   作者:*黑桃~A*#丨???????  
這篇文章主要介紹了Java多線程事務(wù)回滾@Transactional失效處理方案,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下

背景介紹

1,最近有一個大數(shù)據(jù)量插入的操作入庫的業(yè)務(wù)場景,需要先做一些其他修改操作,然后在執(zhí)行插入操作,由于插入數(shù)據(jù)可能會很多,用到多線程去拆分數(shù)據(jù)并行處理來提高響應(yīng)時間,如果有一個線程執(zhí)行失敗,則全部回滾。

2,在spring中可以使用@Transactional注解去控制事務(wù),使出現(xiàn)異常時會進行回滾,在多線程中,這個注解則不會生效,如果主線程需要先執(zhí)行一些修改數(shù)據(jù)庫的操作,當(dāng)子線程在進行處理出現(xiàn)異常時,主線程修改的數(shù)據(jù)則不會回滾,導(dǎo)致數(shù)據(jù)錯誤。

3,下面用一個簡單示例演示多線程事務(wù)。

公用的類和方法

示例事務(wù)不成功操作

/**
* 測試多線程事務(wù).
* @param employeeDOList
*/
@Override
@Transactional
public void saveThread(List<EmployeeDO> employeeDOList) {
try {
//先做刪除操作,如果子線程出現(xiàn)異常,此操作不會回滾
this.getBaseMapper().delete(null);
//獲取線程池
ExecutorService service = ExecutorConfig.getThreadPool();
//拆分數(shù)據(jù),拆分5份
List<List<EmployeeDO>> lists=averageAssign(employeeDOList, 5);
//執(zhí)行的線程
Thread []threadArray = new Thread[lists.size()];
//監(jiān)控子線程執(zhí)行完畢,再執(zhí)行主線程,要不然會導(dǎo)致主線程關(guān)閉,子線程也會隨著關(guān)閉
CountDownLatch countDownLatch = new CountDownLatch(lists.size());
AtomicBoolean atomicBoolean = new AtomicBoolean(true);
for (int i =0;i<lists.size();i++){
if (i==lists.size()-1){
atomicBoolean.set(false);
}
List<EmployeeDO> list = lists.get(i);
threadArray[i] = new Thread(() -> {
try {
//最后一個線程拋出異常
if (!atomicBoolean.get()){
throw new ServiceException("001","出現(xiàn)異常");
}
//批量添加,mybatisPlus中自帶的batch方法
this.saveBatch(list);
}finally {
countDownLatch.countDown();
}

});
}
for (int i = 0; i <lists.size(); i++){
service.execute(threadArray[i]);
}
//當(dāng)子線程執(zhí)行完畢時,主線程再往下執(zhí)行
countDownLatch.await();
System.out.println("添加完畢");
}catch (Exception e){
log.info("error",e);
throw new ServiceException("002","出現(xiàn)異常");
}finally {
connection.close();
}
}

數(shù)據(jù)庫中存在一條數(shù)據(jù):

//測試用例
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { ThreadTest01.class, MainApplication.class})
public class ThreadTest01 {

@Resource
private EmployeeBO employeeBO;

/**
* 測試多線程事務(wù).
* @throws InterruptedException
*/
@Test
public void MoreThreadTest2() throws InterruptedException {
int size = 10;
List<EmployeeDO> employeeDOList = new ArrayList<>(size);
for (int i = 0; i<size;i++){
EmployeeDO employeeDO = new EmployeeDO();
employeeDO.setEmployeeName("lol"+i);
employeeDO.setAge(18);
employeeDO.setGender(1);
employeeDO.setIdNumber(i+"XX");
employeeDO.setCreatTime(Calendar.getInstance().getTime());
employeeDOList.add(employeeDO);
}
try {
employeeBO.saveThread(employeeDOList);
System.out.println("添加成功");
}catch (Exception e){
e.printStackTrace();
}
}
}

測試結(jié)果:

可以發(fā)現(xiàn)子線程組執(zhí)行時,有一個線程執(zhí)行失敗,其他線程也會拋出異常,但是主線程中執(zhí)行的刪除操作,沒有回滾,@Transactional注解沒有生效。

使用sqlSession控制手動提交事務(wù)

@Resource
SqlContext sqlContext;
/**
* 測試多線程事務(wù).
* @param employeeDOList
*/
@Override
public void saveThread(List<EmployeeDO> employeeDOList) throws SQLException {
// 獲取數(shù)據(jù)庫連接,獲取會話(內(nèi)部自有事務(wù))
SqlSession sqlSession = sqlContext.getSqlSession();
Connection connection = sqlSession.getConnection();
try {
// 設(shè)置手動提交
connection.setAutoCommit(false);
//獲取mapper
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
//先做刪除操作
employeeMapper.delete(null);
//獲取執(zhí)行器
ExecutorService service = ExecutorConfig.getThreadPool();
List<Callable<Integer>> callableList = new ArrayList<>();
//拆分list
List<List<EmployeeDO>> lists=averageAssign(employeeDOList, 5);
AtomicBoolean atomicBoolean = new AtomicBoolean(true);
for (int i =0;i<lists.size();i++){
if (i==lists.size()-1){
atomicBoolean.set(false);
}
List<EmployeeDO> list = lists.get(i);
//使用返回結(jié)果的callable去執(zhí)行,
Callable<Integer> callable = () -> {
//讓最后一個線程拋出異常
if (!atomicBoolean.get()){
throw new ServiceException("001","出現(xiàn)異常");
}
return employeeMapper.saveBatch(list);
};
callableList.add(callable);
}
//執(zhí)行子線程
List<Future<Integer>> futures = service.invokeAll(callableList);
for (Future<Integer> future:futures) {
//如果有一個執(zhí)行不成功,則全部回滾
if (future.get()<=0){
connection.rollback();
return;
}
}
connection.commit();
System.out.println("添加完畢");
}catch (Exception e){
connection.rollback();
log.info("error",e);
throw new ServiceException("002","出現(xiàn)異常");
}finally {
connection.close();
}
}
// sql
<insert id="saveBatch" parameterType="List">
INSERT INTO
employee (employee_id,age,employee_name,birth_date,gender,id_number,creat_time,update_time,status)
values
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.employeeId},
#{item.age},
#{item.employeeName},
#{item.birthDate},
#{item.gender},
#{item.idNumber},
#{item.creatTime},
#{item.updateTime},
#{item.status}
)
</foreach>
</insert>

數(shù)據(jù)庫中一條數(shù)據(jù):

測試結(jié)果:拋出異常,

刪除操作的數(shù)據(jù)回滾了,數(shù)據(jù)庫中的數(shù)據(jù)依舊存在,說明事務(wù)成功了。

成功操作示例:

@Resource
SqlContext sqlContext;
/**
* 測試多線程事務(wù).
* @param employeeDOList
*/
@Override
public void saveThread(List<EmployeeDO> employeeDOList) throws SQLException {
// 獲取數(shù)據(jù)庫連接,獲取會話(內(nèi)部自有事務(wù))
SqlSession sqlSession = sqlContext.getSqlSession();
Connection connection = sqlSession.getConnection();
try {
// 設(shè)置手動提交
connection.setAutoCommit(false);
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
//先做刪除操作
employeeMapper.delete(null);
ExecutorService service = ExecutorConfig.getThreadPool();
List<Callable<Integer>> callableList = new ArrayList<>();
List<List<EmployeeDO>> lists=averageAssign(employeeDOList, 5);
for (int i =0;i<lists.size();i++){
List<EmployeeDO> list = lists.get(i);
Callable<Integer> callable = () -> employeeMapper.saveBatch(list);
callableList.add(callable);
}
//執(zhí)行子線程
List<Future<Integer>> futures = service.invokeAll(callableList);
for (Future<Integer> future:futures) {
if (future.get()<=0){
connection.rollback();
return;
}
}
connection.commit();
System.out.println("添加完畢");
}catch (Exception e){
connection.rollback();
log.info("error",e);
throw new ServiceException("002","出現(xiàn)異常");
// throw new ServiceException(ExceptionCodeEnum.EMPLOYEE_SAVE_OR_UPDATE_ERROR);
}
}

測試結(jié)果:

數(shù)據(jù)庫中數(shù)據(jù):

刪除的刪除了,添加的添加成功了,測試成功。

到此這篇關(guān)于Java多線程事務(wù)回滾@Transactional失效處理方案的文章就介紹到這了,更多相關(guān)Java Transactional失效內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • MyBatis中的關(guān)聯(lián)關(guān)系配置與多表查詢的操作代碼

    MyBatis中的關(guān)聯(lián)關(guān)系配置與多表查詢的操作代碼

    本文介紹了在MyBatis中配置和使用一對多和多對多關(guān)系的方法,通過合理的實體類設(shè)計、Mapper接口和XML文件的配置,我們可以方便地進行多表查詢,并豐富了應(yīng)用程序的功能和靈活性,需要的朋友可以參考下
    2023-09-09
  • Java為什么基本數(shù)據(jù)類型不需要進行創(chuàng)建對象?

    Java為什么基本數(shù)據(jù)類型不需要進行創(chuàng)建對象?

    今天小編就為大家分享一篇關(guān)于Java為什么基本數(shù)據(jù)類型不需要進行創(chuàng)建對象?,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-04-04
  • 30分鐘入門Java8之lambda表達式學(xué)習(xí)

    30分鐘入門Java8之lambda表達式學(xué)習(xí)

    本篇文章主要介紹了30分鐘入門Java8之lambda表達式學(xué)習(xí),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • hibernate批量操作實例詳解

    hibernate批量操作實例詳解

    這篇文章主要介紹了hibernate批量操作,結(jié)合實例形式分析了Hibernate實現(xiàn)批量插入,更新及刪除等操作的具體實現(xiàn)技巧,需要的朋友可以參考下
    2016-03-03
  • java銀行管理系統(tǒng)源碼

    java銀行管理系統(tǒng)源碼

    這篇文章主要為大家詳細介紹了java銀行管理系統(tǒng)源碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-12-12
  • Java SHA-256加密的兩種實現(xiàn)方法詳解

    Java SHA-256加密的兩種實現(xiàn)方法詳解

    這篇文章主要介紹了Java SHA-256加密的兩種實現(xiàn)方法,結(jié)合實例形式分析了java實現(xiàn)SHA-256加密的實現(xiàn)代碼與相關(guān)注意事項,需要的朋友可以參考下
    2017-08-08
  • java學(xué)習(xí)筆記之eclipse+tomcat 配置

    java學(xué)習(xí)筆記之eclipse+tomcat 配置

    俗話說:工欲善其事必先利其器,既然要學(xué)習(xí)java,首先把java的開發(fā)環(huán)境搗鼓一下吧,這里我們來談?wù)別clipse+tomcat的配置方法。
    2014-11-11
  • 使用controller傳boolean形式值

    使用controller傳boolean形式值

    這篇文章主要介紹了使用controller傳boolean形式值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • 正確結(jié)束Java線程的方法

    正確結(jié)束Java線程的方法

    線程的啟動很簡單,但用戶可能隨時取消任務(wù),怎么樣讓跑起來的線程正確地結(jié)束,這是今天要討論的話題。下面小編來和大家一起學(xué)習(xí)一下吧
    2019-05-05
  • SpringMVC框架如何與Junit整合看這個就夠了

    SpringMVC框架如何與Junit整合看這個就夠了

    這篇文章主要介紹了SpringMVC框架如何與Junit整合看這個就夠了,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-05-05

最新評論