原文:https://juejin.im/post/5902e087da2f60005df05c3d
-------------------------------------------------------------------------------------------------------------------------------------
摘要
名為 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) 會給出錯誤的時區信息。
debug variables
如圖所示,本機默認時區是 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 被轉換為會話時區的時間字符串了。問題到此已然明晰:
- JDBC 誤認為會話時區在 CST-5
- JBDC 把 Timestamp+0 轉為 CST-5 的 String-5
- 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 服務器,建議在維護時間進行。
