如何在Play Framework 2.0中将时区设置为UTC,适用于生产和测试?

3
我们希望我们的Play Framework 2.0 Scala应用程序在应用服务器和MySQL数据库服务器中处理所有日期和时间信息时都使用UTC时间。关键是:
- 不改变部署环境 - 不改变CI(测试)环境 - 不改变本地(开发)环境
有没有标准的最佳实践来做到这一点?我们希望测试在UTC时间下运行,而不必在所有命令行上传递-Duser.timezone = GMT。同样,通过play start启动服务器也是如此。
1个回答

8

这比我们预期的要简单。

首先,在application.conf文件中,按照另一个StackOverflow问题中描述的方式配置JDBC URL参数:

# Set MySQL Connector/J to use UTC server connection and time conversions
#   see https://dev59.com/nGkv5IYBdhLWcg3wlR31
db.default.url="jdbc:mysql://localhost/database?useGmtMillisForDatetimes=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&useTimezone=true&serverTimezone=UTC"

其次,在 Build.scala 文件中,设置Java系统属性和默认值:
// Setting this property here forces the JVM to run in UTC time, 
// both for test (`play test`) and development (`play start`) modes, 
// but not for production (`play dist`).
System.setProperty("user.timezone", "GMT")
TimeZone.setDefault(TimeZone.getTimeZone("GMT"))

这两个变更将同时处理测试(play test)和开发(play start)模式。
对于生产环境(play dist),启动前仍需设置属性。例如:
1. 编辑生成的start脚本,添加export _JAVA_OPTIONS=-Duser.timezone=GMT 2. 使用-Duser.timezone=GMT调用start脚本 3. 在调用System.setProperty("user.timezone", "GMT")后在现有JVM中启动

糟糕,原始解决方案只适用于测试(play test)和开发(play start)。更新的解决方案支持生产环境(play dist),该环境不运行Build.scala文件。 - ms-tg
受此启发!在我们的情况下,只需要两件事:1)在slick.dbs.default.db.url中添加serverTimezone=UTC 2)使用-Duser.timezone=UTC配置sbt运行。 - Hahn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接