一次 JDBC 與 MySQL 因 「CST」 時區協商誤解致使時間差了 14 或 13 小時的排錯經歷

摘要

名爲 CST 的時區是一個很混亂的時區,在與 MySQL 協商會話時區時,Java 會誤覺得是 CST -0500,而非 CST +0800java

CST 時區

名爲 CST 的時區是一個很混亂的時區,有四種含義:mysql

  • 美國中部時間 Central Standard Time (USA) UTC-06:00
  • 澳大利亞中部時間 Central Standard Time (Australia) UTC+09:30
  • 中國標準時 China Standard Time UTC+08:00
  • 古巴標準時 Cuba Standard Time UTC-04:00

今天是「4月28日」。爲何提到日期?由於美國從「3月11日」至「11月7日」實行夏令時,美國中部時間改成 UTC-05:00,與 UTC+08:00 相差 13 小時。sql

排錯過程

在項目中,偶然發現數據庫中存儲的 Timestamp 字段的 unix_timestamp() 值比真實值少了 13 個小時。經過調試追蹤,發現了 com.mysql.cj.jdbc 裏的時區協商有問題。數據庫

當 JDBC 與 MySQL 開始創建鏈接時,會調用 com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer() 獲取服務器參數,其中咱們看到調用 this.session.configureTimezone() 函數,它負責配置時區。服務器

public void configureTimezone() {
    String configuredTimeZoneOnServer = getServerVariable("time_zone");

    if ("SYSTEM".equalsIgnoreCase(configuredTimeZoneOnServer)) {
        configuredTimeZoneOnServer = getServerVariable("system_time_zone");
    }

    String canonicalTimezone = getPropertySet().getStringReadableProperty(PropertyDefinitions.PNAME_serverTimezone).getValue();

    if (configuredTimeZoneOnServer != null) {
        // user can override this with driver properties, so don't detect if that's the case
        if (canonicalTimezone == null || StringUtils.isEmptyOrWhitespaceOnly(canonicalTimezone)) {
            try {
                canonicalTimezone = TimeUtil.getCanonicalTimezone(configuredTimeZoneOnServer, getExceptionInterceptor());
            } catch (IllegalArgumentException iae) {
                throw ExceptionFactory.createException(WrongArgumentException.class, iae.getMessage(), getExceptionInterceptor());
            }
        }
    }

    if (canonicalTimezone != null && canonicalTimezone.length() > 0) {
        this.serverTimezoneTZ = TimeZone.getTimeZone(canonicalTimezone);

        // The Calendar class has the behavior of mapping unknown timezones to 'GMT' instead of throwing an exception, so we must check for this...
        if (!canonicalTimezone.equalsIgnoreCase("GMT")
            && this.serverTimezoneTZ.getID().equals("GMT")) {
            throw ...
        }
    }

    this.defaultTimeZone = this.serverTimezoneTZ;
}複製代碼

追蹤代碼可知,當 MySQL 的 time_zone 值爲 SYSTEM 時,會取 system_time_zone 值做爲協調時區。session

讓咱們登陸到 MySQL 服務器驗證這兩個值:app

mysql> show variables like '%time_zone%';
+------------------+--------+
| Variable_name    | Value  |
+------------------+--------+
| system_time_zone | CST    |
| time_zone        | SYSTEM |
+------------------+--------+
2 rows in set (0.00 sec)複製代碼

重點在這裏!若 String configuredTimeZoneOnServer 獲得的是 CST 那麼 Java 會誤覺得這是 CST -0500,所以 TimeZone.getTimeZone(canonicalTimezone) 會給出錯誤的時區信息。ide

debug variables

如圖所示,本機默認時區是 Asia/Shanghai +0800,誤認爲服務器時區爲 CST -0500,實際上服務器是 CST +0800函數

咱們會想到,即使時區有誤解,若是 Timestamp 是以 long 表示的時間戳傳輸,也不會出現問題,下面讓咱們追蹤到 com.mysql.cj.jdbc.PreparedStatement.setTimestamp()this

public void setTimestamp(int parameterIndex, Timestamp x) throws java.sql.SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        setTimestampInternal(parameterIndex, x, this.session.getDefaultTimeZone());
    }
}複製代碼

注意到這裏 this.session.getDefaultTimeZone() 獲得的是剛纔那個 CST -0500

private void setTimestampInternal(int parameterIndex, Timestamp x, TimeZone tz) throws SQLException {
    if (x == null) {
        setNull(parameterIndex, MysqlType.TIMESTAMP);
    } else {
        if (!this.sendFractionalSeconds.getValue()) {
            x = TimeUtil.truncateFractionalSeconds(x);
        }

        this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = MysqlType.TIMESTAMP;

        if (this.tsdf == null) {
            this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss", Locale.US);
        }

        this.tsdf.setTimeZone(tz);

        StringBuffer buf = new StringBuffer();
        buf.append(this.tsdf.format(x));
        if (this.session.serverSupportsFracSecs()) {
            buf.append('.');
            buf.append(TimeUtil.formatNanos(x.getNanos(), true));
        }
        buf.append('\'');

        setInternal(parameterIndex, buf.toString());
    }
}複製代碼

原來 Timestamp 被轉換爲會話時區的時間字符串了。問題到此已然明晰:

  1. JDBC 誤認爲會話時區在 CST-5
  2. JBDC 把 Timestamp+0 轉爲 CST-5 的 String-5
  3. MySQL 認爲會話時區在 CST+8,將 String-5 轉爲 Timestamp-13

最終結果相差 13 個小時!若是處在冬令時還會相差 14 個小時!

解決方案

解決辦法也很簡單,明確指定 MySQL 數據庫的時區,不使用引起誤解的 CST

mysql> set global time_zone = '+08:00';
Query OK, 0 rows affected (0.00 sec)

mysql> set time_zone = '+08:00';
Query OK, 0 rows affected (0.00 sec)複製代碼

或者修改 my.cnf 文件,在 [mysqld] 節下增長 default-time-zone = '+08:00'

修改時區操做影響深遠,須要重啓 MySQL 服務器,建議在維護時間進行。

相關文章
相關標籤/搜索