成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Spring事務超時到底是怎么回事?

開發 架構
Spring事務超時是指一個事務在執行中最長的允許時間。如果事務在超時時間內未能完成,則會自動回滾。超時時間可以通過設置來控制,以確保事務在規定的時間內完成或回滾,避免數據一致性問題。

環境:Spring5.3.23

Spring事務超時是指一個事務在執行中最長的允許時間。如果事務在超時時間內未能完成,則會自動回滾。超時時間可以通過設置來控制,以確保事務在規定的時間內完成或回滾,避免數據一致性問題。

在工作中你有配置事務的超時時間嗎?如何進行配置事務超時時間?

1. 配置事務超時時間

注解方式:

// 這里單位是s
@Transactional(timeout = 2)
public void save() {
}

編程方式1:

@Resource
private PlatformTransactionManager tm ;


DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
definition.setTimeout(2) ;

編程方式2:

@Resource
private PlatformTransactionManager tm ;
public void update() {
  TransactionTemplate template = new TransactionTemplate(tm) ;
  template.setTimeout(2) ;
  template.execute(new TransactionCallback<Object>() {
    @Override
    public Object doInTransaction(TransactionStatus status) {
      // ...
      return null ;
    }
  }) ;
}

以上3種方式讀可以進行事務超時的設置,什么情況下才能算是事務超時呢?

2. 準備環境

準備一張2000w數據的表

圖片圖片

表字段信息如下:

圖片圖片

此表除主鍵外沒有任何的索引。

圖片圖片

3. 模擬事務超時

  • 測試1

統計查詢表的數據量,將該操作放到一個事務中,同時設置事務的超時時間。

// 將超時時間設置為20s
@Transactional(timeout = 20)
public void query() {
  long start = System.currentTimeMillis() ;
  jdbcTemplate.execute("select count(*) from p_user") ;
  System.out.println("耗時:" + (System.currentTimeMillis() - start) + "毫秒") ;
}

執行結果:

耗時:3198毫秒

接下來將超時時間改成3s

執行結果如下:

13:56:01.425 [main] WARN  c.zaxxer.hikari.pool.ProxyConnection - HikariPool-1 - Connection com.mysql.cj.jdbc.ConnectionImpl@504ecd marked as broken because of SQLSTATE(null), ErrorCode(0)
com.mysql.cj.jdbc.exceptions.MySQLTimeoutException: Statement cancelled due to timeout or client request
  at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:113)
  at com.mysql.cj.jdbc.StatementImpl.checkCancelTimeout(StatementImpl.java:2167)

從異常信息看到拋出了超時異常。這里的超時是sql執行的超時,是由我們的驅動程序拋出的異常。

  • 測試2

模擬其它非數據庫操作耗時,而這個是在執行數據庫操作之前

@Transactional(timeout = 2)
public void query() {
  long start = System.currentTimeMillis() ;
  try {
    TimeUnit.SECONDS.sleep(3) ;
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  // 執行非常簡單的操作
  jdbcTemplate.execute("select 1") ;
  System.out.println("耗時:" + (System.currentTimeMillis() - start) + "毫秒") ;
}

執行結果:

14:08:44.000 [main] DEBUG o.s.jdbc.core.JdbcTemplate - Executing SQL statement [select 1]
Exception in thread "main" org.springframework.transaction.TransactionTimedOutException: Transaction timed out: deadline was Wed Oct 11 14:08:42 CST 2023
  at org.springframework.transaction.support.ResourceHolderSupport.checkTransactionTimeout(ResourceHolderSupport.java:155)

拋出了超時異常,而這個異常是由Spring框架拋出的。

  • 測試3

模擬其它非數據庫操作耗時,而這個是在執行數據庫操作之后,適當調整上面的代碼順序

@Transactional(timeout = 2)
public void query() {
  long start = System.currentTimeMillis() ;
  jdbcTemplate.execute("select 1") ;
  try {
    TimeUnit.SECONDS.sleep(3) ;
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  System.out.println("耗時:" + (System.currentTimeMillis() - start) + "毫秒") ;
}

執行結果:

耗時:3015毫秒

程序正常運行

  • 測試4

在測試3的基礎上,最后再次執行數據庫相關的操作

@Transactional(timeout = 2)
public void query() {
  long start = System.currentTimeMillis() ;
  jdbcTemplate.execute("select 1") ;
  try {
    TimeUnit.SECONDS.sleep(3) ;
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  System.out.println("耗時:" + (System.currentTimeMillis() - start) + "毫秒") ;
  // 再次執行數據庫相關操作
  jdbcTemplate.execute("select 1") ;
}

執行結果:

耗時:3024毫秒
14:14:38.257 [main] DEBUG o.s.jdbc.core.JdbcTemplate - Executing SQL statement [select 1]
Exception in thread "main" org.springframework.transaction.TransactionTimedOutException: Transaction timed out: deadline was Wed Oct 11 14:14:37 CST 2023
  at org.springframework.transaction.support.ResourceHolderSupport.checkTransactionTimeout(ResourceHolderSupport.java:155)

第一個數據庫操作,沒有拋出異常,直到第二個執行時拋出了異常。

總結:      事務方法開始執行時就開始計時,在執行到數據庫操作時判斷當前的執行時間點是否已經超過了設置的超時時間,如果是則拋出Timeout異常。

4. 事務超時原理

在開始一個事務時會在DataSourceTransactionManager#doBegin方法中設置超時時間

protected void doBegin(Object transaction, TransactionDefinition definition) {
  int timeout = determineTimeout(definition);
  if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
    // 如果注解@Transactional中設置了timeout,則設置超時時間
    txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
  }
}
protected int determineTimeout(TransactionDefinition definition) {
  if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
    return definition.getTimeout();
  }
  return getDefaultTimeout();
}

當通過JdbcTemplate操作數據庫時,還會執行如下操作

public class JdbcTemplate {
  private <T> T execute(StatementCallback<T> action, boolean closeResources) {
    Statement stmt = null;
    try {
      stmt = con.createStatement();
      // 配置Statement對象,這其中會設置超時時間
      applyStatementSettings(stmt);
      // ...
      return result;
    }
  }  
  protected void applyStatementSettings(Statement stmt) throws SQLException {
    // ...
    // getQueryTimeout方法返回的是當前JdbcTemplate對象中設置d餓超時時間
    DataSourceUtils.applyTimeout(stmt, getDataSource(), getQueryTimeout());
  }
}

DataSourceUtils工具類

public abstract class DataSourceUtils {
  public static void applyTimeout(Statement stmt, @Nullable DataSource dataSource, int timeout) throws SQLException {
    ConnectionHolder holder = null;
    if (dataSource != null) {
      holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
    }
    // 如果當前事務執行配置了超時時間
    if (holder != null && holder.hasTimeout()) {
      // 剩余事務超時將覆蓋指定的值。
      stmt.setQueryTimeout(holder.getTimeToLiveInSeconds());
    }
    else if (timeout >= 0) {
      // No current transaction timeout -> apply specified value.
      stmt.setQueryTimeout(timeout);
    }
  }  
}

ResourceHolderSupport類

public abstract class ResourceHolderSupport implements ResourceHolder { 
  public int getTimeToLiveInSeconds() {
    double diff = ((double) getTimeToLiveInMillis()) / 1000;
    int secs = (int) Math.ceil(diff);
    // 檢查超時時間
    checkTransactionTimeout(secs <= 0);
    return secs;
  }
  private void checkTransactionTimeout(boolean deadlineReached) throws TransactionTimedOutException {
    if (deadlineReached) {
      // 設置事務回滾
      setRollbackOnly();
      // 拋出異常
      throw new TransactionTimedOutException("Transaction timed out: deadline was " + this.deadline);
    }
  }
}

完畢!!!

責任編輯:武曉燕 來源: Spring全家桶實戰案例源碼
相關推薦

2022-04-15 08:54:39

PythonAsync代碼

2021-10-15 21:16:00

手機內存漏洞

2019-07-23 15:34:29

MySQL存儲引擎

2023-03-29 08:24:30

2018-01-28 13:59:23

小程序微信開發者

2015-05-29 09:34:13

2018-03-13 10:32:43

2022-05-26 11:36:12

APK文件小米

2010-04-20 09:55:37

2020-02-18 11:19:36

物聯網病毒物聯網IOT

2022-01-25 20:23:21

聯邦通信委員會聯邦航空管理局5G

2020-08-12 09:10:16

AI芯片AI人工智能

2021-06-04 11:10:04

JavaScript開發代碼

2020-02-04 17:42:17

寬帶運營商攜號轉網

2013-04-18 09:56:05

2021-05-11 11:51:15

飛機Wi-Fi通信

2023-03-05 15:41:58

MySQL日志暴漲

2016-11-22 19:54:56

點擊率預估推薦算法廣告

2023-06-13 18:45:00

研究監督

2024-01-08 08:35:28

閉包陷阱ReactHooks
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产日本精品视频 | 精品久久久久久久人人人人传媒 | 男人阁久久 | 国产一区二区三区在线看 | 日韩精品一区二区三区在线观看 | 国产综合网址 | 亚洲精品一区二三区不卡 | 天天色影视综合 | www国产成人 | 91资源在线 | 精产嫩模国品一二三区 | 亚洲另类视频 | 欧美xxxx黑人又粗又长 | 亚洲欧美一区二区三区1000 | 欧美狠狠操 | 中文一区| 亚洲成av片人久久久 | 国产毛片在线看 | 欧美日韩国产一区 | 黄a网| 亚洲精品福利在线 | 精品国产一区探花在线观看 | 亚洲精品68久久久一区 | 美女视频一区 | 成人免费视频一区 | 日日干夜夜操 | 香蕉一区| 国产一区二区三区四区五区3d | 亚洲欧美v| 一区二区三区不卡视频 | 亚洲国产精品视频 | 成人免费视频网站 | 久久久久久国产精品 | 狠狠干天天干 | 99热在这里只有精品 | 中文字幕在线一区二区三区 | 欧美一级欧美一级在线播放 | 久久亚洲一区二区三区四区 | 欧美日韩精品一区二区三区视频 | 欧美日韩不卡合集视频 | 最新av在线网址 |