SpringBoot时间戳与MySql数据库记录相差14小时排错

From: http://www.cnblogs.com/jason1990/archive/2018/11/28/10032181.html

项目中遇到存储的时间戳与真实时间相差14小时的现象,以下为解决步骤.

问题

CREATE TABLE `incident` (`id` int(11) NOT NULL AUTO_INCREMENT,`created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,`recovery_time` timestamp NULL DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4;

以上为数据库建表语句,其中created_time是插入记录时自动设置,recovery_time需要手动进行设置.
测试时发现,created_time为正确的北京时间,然而recovery_time则与设置时间相差14小时.

尝试措施

jvm时区设置

//设置jvm默认时间
System.setProperty("user.timezone", "UTC");

数据库时区查询

查看数据库时区设置:

show variables like '%time_zone%';
--- 查询结果如下所示:
--- system_time_zone: CST
--- time_zone:SYSTEM

查询CST发现其指代比较混乱,有四种含义(参考网址:https://juejin.im/post/5902e087da2f60005df05c3d):

  • 美国中部时间 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

此处发现如果按照美国中部时间进行推算,相差14小时,与Bug吻合.

验证过程

MyBatis转换

代码中,时间戳使用Instant进行存储,因此跟踪package org.apache.ibatis.type下的InstantTypeHandler.

@UsesJava8
public class InstantTypeHandler extends BaseTypeHandler<Instant> {@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, Instant parameter, JdbcType jdbcType) throws SQLException {ps.setTimestamp(i, Timestamp.from(parameter));}//...代码shenglve
}

调试时发现parameter为正确的UTC时.
函数中调用Timestamp.fromInstant转换为Timestamp实例,检查无误.

    /*** Sets the designated parameter to the given <code>java.sql.Timestamp</code> value.* The driver* converts this to an SQL <code>TIMESTAMP</code> value when it sends it to the* database.** @param parameterIndex the first parameter is 1, the second is 2, ...* @param x the parameter value* @exception SQLException if parameterIndex does not correspond to a parameter* marker in the SQL statement; if a database access error occurs or* this method is called on a closed <code>PreparedStatement</code>     */void setTimestamp(int parameterIndex, java.sql.Timestamp x)throws SQLException;

继续跟踪setTimestamp接口,其具体解释见代码注释.

Sql Driver转换

项目使用com.mysql.cj.jdbc驱动,跟踪其setTimestampClientPreparedStatement类下的具体实现(PreparedStatementWrapper类下实现未进入).

    @Overridepublic void setTimestamp(int parameterIndex, Timestamp x) throws java.sql.SQLException {synchronized (checkClosed().getConnectionMutex()) {((PreparedQuery<?>) this.query).getQueryBindings().setTimestamp(getCoreParameterIndex(parameterIndex), x);}}

继续跟踪上端代码中的getQueryBindings().setTimestamp()实现(com.mysql.cj.ClientPreparedQueryBindings).

    @Overridepublic void setTimestamp(int parameterIndex, Timestamp x, Calendar targetCalendar, int fractionalLength) {if (x == null) {setNull(parameterIndex);} else {x = (Timestamp) x.clone();if (!this.session.getServerSession().getCapabilities().serverSupportsFracSecs()|| !this.sendFractionalSeconds.getValue() && fractionalLength == 0) {x = TimeUtil.truncateFractionalSeconds(x);}if (fractionalLength < 0) {// default to 6 fractional positionsfractionalLength = 6;}x = TimeUtil.adjustTimestampNanosPrecision(x, fractionalLength, !this.session.getServerSession().isServerTruncatesFracSecs());//注意此处时区转换this.tsdf = TimeUtil.getSimpleDateFormat(this.tsdf, "''yyyy-MM-dd HH:mm:ss", targetCalendar,targetCalendar != null ? null : this.session.getServerSession().getDefaultTimeZone());StringBuffer buf = new StringBuffer();buf.append(this.tsdf.format(x));if (this.session.getServerSession().getCapabilities().serverSupportsFracSecs()) {buf.append('.');buf.append(TimeUtil.formatNanos(x.getNanos(), 6));}buf.append('\'');setValue(parameterIndex, buf.toString(), MysqlType.TIMESTAMP);}}

注意此处时区转换,会调用如下语句获取默认时区:

this.session.getServerSession().getDefaultTimeZone()

获取TimeZone数据,具体如下图所示:

TimeZone定义

检查TimeZone类中offset含义,具体如下所示:

    /*** Gets the time zone offset, for current date, modified in case of* daylight savings. This is the offset to add to UTC to get local time.* <p>* This method returns a historically correct offset if an* underlying <code>TimeZone</code> implementation subclass* supports historical Daylight Saving Time schedule and GMT* offset changes.** @param era the era of the given date.* @param year the year in the given date.* @param month the month in the given date.* Month is 0-based. e.g., 0 for January.* @param day the day-in-month of the given date.* @param dayOfWeek the day-of-week of the given date.* @param milliseconds the milliseconds in day in <em>standard</em>* local time.** @return the offset in milliseconds to add to GMT to get local time.** @see Calendar#ZONE_OFFSET* @see Calendar#DST_OFFSET*/public abstract int getOffset(int era, int year, int month, int day,int dayOfWeek, int milliseconds);

offset表示本地时间UTC时的时间间隔(ms).
计算数值offset,发现其表示美国中部时间,即UTC-06:00.

  • Driver推断Session时区为UTC-6;
  • DriverTimestamp转换为UTC-6String;
  • MySql认为Session时区在UTC+8,将String转换为UTC+8.

因此,最终结果相差14小时,bug源头找到.

解决方案

参照https://juejin.im/post/5902e087da2f60005df05c3d.

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)

告知运维设置时区,重启MySql服务,问题解决.

此外,作为防御措施,可以在jdbc url中设置时区(如此设置可以不用修改MySql配置):

jdbc:mysql://localhost:3306/table_name?useTimezone=true&serverTimezone=GMT%2B8

此时,就告知连接进行时区转换,并且时区为UTC+8.

PS:
如果您觉得我的文章对您有帮助,可以扫码领取下红包,谢谢!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/402614.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HDU 1233 还是畅通工程(最小生成树)

传送门 还是畅通工程 Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 41447 Accepted Submission(s): 18920 Description 某省调查乡村交通状况&#xff0c;得到的统计表中列出了任意两村庄间的距离。省政府“畅…

出了本练内功的书:《完美软件开发:方法与逻辑》

首先说下什么叫“完美软件开发”&#xff0c;想象一下&#xff0c;完美的圆在现实中是不存在的&#xff0c;现实中的圆只能是对完美的圆的回归&#xff0c;但完美的圆描述了圆的构成规则&#xff0c;完美软件开发意义与此相同&#xff0c;它试图描述软件开发的规则和铁律。但既…

Springboot后台接收前端Date类型

From: https://my.oschina.net/zicheng/blog/2963117 这个问题不是专门针对Springboot的&#xff0c;Springmvc也同样适用于这一个问题。 昨的是Springboot前后端分离的项目&#xff0c;今天和前端对接口发现前端的请求走不到后台&#xff0c;检查了请求什么的都没有问题&…

关于jTopo的引用

jTopo是一款 2 D和3D模型展示的插件&#xff0c;不过目前文档不是很齐全&#xff0c;刚开始看的时候就有点懵了&#xff0c;因为你在网上很难找到jTopo的资料。下面我就介绍一下jTopo 的引用吧。 1、首先在官网上下载到jTopo的包&#xff0c;地址&#xff1a;http://www.jtopo.…

mysql重置root密码方法

2019独角兽企业重金招聘Python工程师标准>>> 1. 先关闭mysqld 2. 运行&#xff1a; mysqld_safe --skip-grant-tables 3. 另开一个窗口&#xff0c;用 mysql -uroot 登录mysql&#xff0c;执行 UPDATE mysql.user SET PasswordPASSWORD(你的密码) WHERE User…

插入排序之C++实现

描述 插入排序是一种简单直观的排序算法。它的基本思想是将一个待排序的数据序列分为已排序和未排序两部分&#xff0c;每次从未排序序列中取出一个元素&#xff0c;然后将它插入到已排序序列的适当位置&#xff0c;直到所有元素都插入完毕&#xff0c;即完成排序。 实现思路…

spring boot使用logback实现多环境日志配置

From: https://blog.csdn.net/vitech/article/details/53812137 软件生存周期中&#xff0c;涉及代码运行的环节有编码、测试和维护阶段&#xff0c;而一套成熟的代码&#xff0c;在此三个阶段&#xff0c;数据库、日志路径、日志级别、线程池大小等配置一般会不一样。作为开发…

IOT(Index Organized Table)

我们知道一般的表都以堆(heap)的形式来组织的&#xff0c;这是无序的组织方式。Oracle还提供了一种有序的表&#xff0c;它就是索引组织表&#xff0c;简称IOT表。IOT表上必须要有主键&#xff0c;而IOT表本身不对应segment&#xff0c;表里所有的数据都存放在主键所在的索引的…

C++中的 :: 用法

::是运算符中等级最高的&#xff0c;它分为三种:1)global scope(全局作用域符&#xff09;&#xff0c;用法&#xff08;::name)2)class scope(类作用域符&#xff09;&#xff0c;用法(class::name)3)namespace scope(命名空间作用域符&#xff09;&#xff0c;用法(namespace…

Spring Boot SLF4J日志实例

From: https://blog.csdn.net/lxh18682851338/article/details/78560295 默认情况下&#xff0c;SLF4j日志记录包含在Spring Boot Web应用程序中&#xff0c;只需要启用它就可以了。 注意&#xff1a;查看此Spring Boot Logback XML模板以了解默认的日志记录模式和配置。 SLF4…

java 反取字符串

public class demo2 {/*** 2 : 将字符串反取出来 新中国好 好国中新*/public static void main(String[] args) {String s "新中国好";s reverse1(s);System.out.println("方法一&#xff1a;" s);s reverse2(s);System.out.println("方法二…

测试使用wiz来发布blog

晚上尝试了下用wiz写随笔并发布&#xff0c;貌似成功了&#xff0c;虽然操作体验和方便性上不如word&#xff0c;但起码它集成了这个简单的功能可以让我用&#xff1a;如果能让我自动新建blog文章并自动定时更新发布就完美了。2013年7月5日19:31:04发现最近开始慢慢重度使用wiz…

Spring在Java Filter注入Bean为Null的问题解决

From: https://www.cnblogs.com/EasonJim/p/7666009.html 在Spring的自动注入中普通的POJO类都可以使用Autowired进行自动注入&#xff0c;但是除了两类&#xff1a;Filter和Servlet无法使用自动注入属性。&#xff08;因为这两个归Web容器管理&#xff09;可以用init&#xf…

关于工作的选择之软件开发还是软件维护的建议

今天是周六休息&#xff0c;好可爱的双休日啊。下周一出差去四平&#xff0c;要和我们单位另外2名工程师一起去给四平的一个公司安装调试一个机房的设备&#xff0c;大概需要三天的时间吧。昨天晚上去个朋友家做客&#xff0c;朋友他侄子大学是学计算机软件的&#xff0c;今年刚…

Mybatis:resultMap的使用总结

From: https://www.cnblogs.com/kenhome/p/7764398.html Mybatis的介绍以及使用&#xff1a;http://www.mybatis.org/mybatis-3/zh/index.html resultMap是Mybatis最强大的元素&#xff0c;它可以将查询到的复杂数据&#xff08;比如查询到几个表中数据&#xff09;映射到一个…

NSOperation, NSOperationQueue 原理探析

通过GNUstep的Foundation来尝试探索下NSOperation&#xff0c;NSOperationQueue 示例程序 写一个简单的程序 - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self configurationQueue]; LDNSOperatio…

MyBatis总结六:resultMap详解(包含多表查询)

From: https://www.cnblogs.com/Alex-zqzy/p/9296039.html 简介&#xff1a;   MyBatis的每一个查询映射的返回类型都是ResultMap&#xff0c;只是当我们提供的返回类型属性是resultType的时候&#xff0c;MyBatis对自动的给我们把对应的值赋给resultType所指定对象的属性&a…

object c 快速构建对象

__block NSNumber *capacity (0);

mysql语句添加索引

1.PRIMARY KEY&#xff08;主键索引&#xff09; mysql>ALTER TABLE table_name ADD PRIMARY KEY ( column ) 2.UNIQUE(唯一索引) mysql>ALTER TABLE table_name ADD UNIQUE (column ) 3.INDEX(普通索引) mysql>ALTER TABLE table…

基于beego一键创建RESTFul应用

2019独角兽企业重金招聘Python工程师标准>>> API应用开发入门 Go是非常适合用来开发API应用的&#xff0c;而且我认为也是Go相对于其他动态语言的最大优势应用。beego在开发API应用方面提供了非常强大和快速的工具&#xff0c;方便用户快速的建立API应用原型&#…