【问题标题】:How to set timezone to UTC in Play Framework 2.0 for both production and tests?如何在 Play Framework 2.0 中为生产和测试设置时区为 UTC?
【发布时间】:2013-03-25 20:22:24
【问题描述】:

我们希望我们的 Play Framework 2.0 Scala 应用程序能够处理应用服务器和 MySQL 数据库服务器中的所有 UTC 日期和时间信息。

诀窍是:

  • 无需更改部署环境
  • 无需更改 CI(测试)环境
  • 无需更改本地(开发)环境

是否有执行此操作的标准最佳实践?我们希望测试在 UTC 中运行,而不必在所有命令行上通过 -Duser.timezone=GMT。同样使用play start 来启动服务器。

【问题讨论】:

    标签: mysql timezone playframework-2.0


    【解决方案1】:

    这比我们预期的要容易。

    首先在application.conf中配置JDBC URL,参数as described on another StackOverflow question

    # Set MySQL Connector/J to use UTC server connection and time conversions
    #   see https://stackoverflow.com/questions/10488529/gettimestamp-does-timezone-converstion-twice-in-mysql-jdbc-connector
    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"))
    

    这两项更改将同时处理 test (play test) 和 development (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)。更新解决方案以支持不运行 Build.scala 的生产 (play dist)
    • 受此启发!仅供参考,在我们的例子中,只需要两件事:1)serverTimezone=UTC in slick.dbs.default.db.url 2)配置 sbt 运行 -Duser.timezone=UTC
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2018-09-13
    • 1970-01-01
    相关资源
    最近更新 更多