Mysql數據庫顯示時間與應用程序獲取到的不一致的問題

轉載:https://juejin.im/post/5902e087da2f60005df05c3d

問題現象:

如下爲通過mysql客戶端命令行獲取到的數據,時間顯示如下:

在前端頁面獲取到的時間如下所示:


顯示相差13小時。

個人操作:

在執行set global time_zone = '+08:00';與set time_zone = '+08:00';後問題得到解決,此方式不需要重啓Mysql!


摘要

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

CST 時區

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

  • 美國中部時間 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 小時。

排錯過程

在項目中,偶然發現數據庫中存儲的 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 值作爲協調時區。

讓我們登錄到 MySQL 服務器驗證這兩個值:

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) 會給出錯誤的時區信息。

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

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

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 服務器,建議在維護時間進行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章