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

诀窍是:

  • 不改变部署环境
  • 不改变 CI(测试)环境
  • 不改变本地(开发)环境

  • 是否有标准的最佳实践来做到这一点?我们希望测试以 UTC 运行,而不必在所有命令行上传递 -Duser.timezone=GMT。使用 play start 启动服务器也是如此。

    最佳答案

    这比我们预期的要容易。

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

    # 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"))
    

    这两个更改将一起处理 测试 ( play test ) 和 开发 ( play start ) 模式。

    对于 生产 ( play dist ),仍然必须在启动前设置该属性。例如,通过:
  • 编辑生成的 start 脚本以添加 export _JAVA_OPTIONS=-Duser.timezone=GMT
  • 使用 start
  • 调用 -Duser.timezone=GMT 脚本
  • 在调用 System.setProperty("user.timezone", "GMT")
  • 后在现有 JVM 中启动

    关于mysql - 如何在 Play Framework 2.0 中将时区设置为 UTC 以进行生产和测试?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15799713/

    10-14 19:27
    查看更多