文档

§生产配置

您可以在生产中配置多种类型的配置。三种主要类型是

每种类型都有不同的配置方法。

§通用配置

Play 具有许多可配置的设置。您可以配置数据库连接 URL、应用程序密钥、HTTP 端口、SSL 配置等。

Play 的大部分配置都定义在各种 .conf 文件中,这些文件使用 HOCON 格式。您将使用的主要配置文件是 application.conf 文件。您可以在项目的 conf/application.conf 中找到此文件。application.conf 文件在运行时从类路径加载(或者您可以覆盖加载位置)。每个项目只能有一个 application.conf

其他 .conf 文件也会加载。库在 reference.conf 文件中定义默认设置。这些文件存储在库的 JAR 中——每个 JAR 一个 reference.conf——并在运行时聚合在一起。reference.conf 文件提供默认值;它们会被 application.conf 文件中定义的任何设置覆盖。

Play 的配置也可以使用系统属性和环境变量来定义。当设置在环境之间发生变化时,这可能很方便;您可以使用 application.conf 用于通用设置,但使用系统属性和环境变量来更改在不同环境中运行应用程序时的设置。

系统属性会覆盖 application.conf 中的设置,而 application.conf 会覆盖各种 reference.conf 文件中的默认设置。

您可以通过多种方式覆盖运行时配置。当设置在不同环境之间有所不同时,这将非常有用;您可以为每个环境动态更改配置。以下是您用于运行时配置的选择

§指定备用配置文件

默认情况下,从类路径加载 application.conf 文件。如果需要,您可以指定备用配置文件

§使用 -Dconfig.resource

这将在应用程序类路径中搜索备用配置文件(您通常在打包之前将这些备用配置文件提供到应用程序 conf/ 目录中)。Play 将会查看 conf/,因此您不必添加 conf/

$ /path/to/bin/<project-name> -Dconfig.resource=prod.conf

§使用 -Dconfig.file

您还可以指定另一个未打包到应用程序工件中的本地配置文件

$ /path/to/bin/<project-name> -Dconfig.file=/opt/conf/prod.conf

请注意,您始终可以使用 include 指令在新的 prod.conf 文件中引用原始配置文件,例如

include "application.conf"

key.to.override=blah

§使用系统属性覆盖配置

有时您不想指定另一个完整的配置文件,而只是覆盖一些特定的键。您可以通过将它们指定为 Java 系统属性来实现

$ /path/to/bin/<project-name> -Dplay.http.secret.key=ad31779d4ee49d5ad5162bf1429c32e2e9933f3b -Ddb.default.password=toto

§使用系统属性指定 HTTP 服务器地址和端口

您可以使用系统属性轻松地提供 HTTP 端口和地址。默认情况下,在 0.0.0.0 地址(所有地址)的 9000 端口上监听。

$ /path/to/bin/<project-name> -Dhttp.port=1234 -Dhttp.address=127.0.0.1

§使用环境变量指定 HTTP 服务器地址和端口

您可以使用环境变量轻松地提供 HTTP 端口和地址,例如在 Linux 中使用 Bash 时

export PLAY_HTTP_PORT=1234
export PLAY_HTTPS_PORT=1235
export PLAY_HTTP_ADDRESS=127.0.0.1

这些变量最后被拾取,这意味着在 application.conf 中或通过系统属性定义的任何端口或地址都将覆盖这些环境变量。

§更改 RUNNING_PID 的路径

可以更改包含已启动应用程序进程 ID 的文件路径。通常,此文件放置在 Play 项目的根目录中,但建议将其放置在重启时会自动清除的位置,例如 /var/run

$ /path/to/bin/<project-name> -Dpidfile.path=/var/run/play.pid

确保目录存在,并且运行 Play 应用程序的用户对该目录具有写入权限。

使用此文件,您可以使用 kill 命令停止应用程序,例如

$ kill $(cat /var/run/play.pid)

要阻止 Play 创建自己的 PID,您可以在 application.conf 文件中将路径设置为 /dev/null

pidfile.path = "/dev/null"

§使用环境变量

您也可以从 application.conf 文件中引用环境变量。

my.key = defaultvalue
my.key = ${?MY_KEY_ENV}

这里,覆盖字段 my.key = ${?MY_KEY_ENV} 如果没有 MY_KEY_ENV 的值,则会消失,但如果您设置了一个环境变量 MY_KEY_ENV(例如),则会使用它。

§服务器配置选项

Play 的默认 HTTP 服务器实现是 Pekko HTTP,它提供了大量调整和配置服务器的方法,包括解析器缓冲区的大小、是否使用保持活动连接等等。

可以在此处查看服务器配置选项的完整列表,包括默认值。

# Copyright (C) from 2022 The Play Framework Contributors <https://github.com/playframework>, 2011-2021 Lightbend Inc. <https://www.lightbend.com>

# Configuration for Play's PekkoHttpServer
play {

  server {
    # The server provider class name
    provider = "play.core.server.PekkoHttpServerProvider"

    pekko {
      # How long to wait when binding to the listening socket
      bindTimeout = 5 seconds

      # How long a request takes until it times out. Set to null or "infinite" to disable the timeout.
      requestTimeout = infinite

      # Enables/disables automatic handling of HEAD requests.
      # If this setting is enabled the server dispatches HEAD requests as GET
      # requests to the application and automatically strips off all message
      # bodies from outgoing responses.
      # Note that, even when this setting is off the server will never send
      # out message bodies on responses to HEAD requests.
      # For Play to work correctly with WebSockets, you should avoid setting this config to "on",
      # see https://github.com/playframework/playframework/pull/7060
      transparent-head-requests = off

      # If this setting is empty the server only accepts requests that carry a
      # non-empty `Host` header. Otherwise it responds with `400 Bad Request`.
      # Set to a non-empty value to be used in lieu of a missing or empty `Host`
      # header to make the server accept such requests.
      # Note that the server will never accept HTTP/1.1 request without a `Host`
      # header, i.e. this setting only affects HTTP/1.1 requests with an empty
      # `Host` header as well as HTTP/1.0 requests.
      # Examples: `www.spray.io` or `example.com:8080`
      default-host-header = ""

      # The default value of the `Server` header to produce if no
      # explicit `Server`-header was included in a response.
      # If this value is null and no header was included in
      # the request, no `Server` header will be rendered at all.
      server-header = null
      server-header = ${?play.server.server-header}

      # Configures the processing mode when encountering illegal characters in
      # header value of response.
      #
      # Supported mode:
      # `error`  : default mode, throw an ParsingException and terminate the processing
      # `warn`   : ignore the illegal characters in response header value and log a warning message
      # `ignore` : just ignore the illegal characters in response header value
      illegal-response-header-value-processing-mode = warn

      # Enables/disables inclusion of an Tls-Session-Info header in parsed
      # messages over Tls transports (i.e., HttpRequest on server side and
      # HttpResponse on client side).
      #
      # See Pekko HTTP `pekko.http.server.parsing.tls-session-info-header` for
      # more information about how this works.
      tls-session-info-header = on

      # The maximum number of requests that are accepted (and dispatched to
      # the application) on one single connection before the first request
      # has to be completed.
      # Incoming requests that would cause the pipelining limit to be exceeded
      # are not read from the connections socket so as to build up "back-pressure"
      # to the client via TCP flow control.
      # A setting of 1 disables HTTP pipelining, since only one request per
      # connection can be "open" (i.e. being processed by the application) at any time.
      # This value must be > 0 and <= 1024.
      # ATTENTION:
      # Only enable HTTP pipelining if you _really_ know what you are doing. Nowadays, HTTP pipelining
      # is mostly used for benchmarks anyway. Basically all web browser and most common clients (like curl)
      # removed support for HTTP pipelining, since most client and server implementations were error prone.
      # Also the implemention used by Play can cause unexpected behaviour, e.g. see
      # https://github.com/playframework/playframework/issues/12351
      pipelining-limit = 1
    }
  }

}

您也可以使用 Netty 作为 HTTP 服务器,它也提供自己的配置。可以在下面查看 Netty 服务器配置的完整列表,包括默认值。

# Copyright (C) from 2022 The Play Framework Contributors <https://github.com/playframework>, 2011-2021 Lightbend Inc. <https://www.lightbend.com>

play.server {

  # The server provider class name
  provider = "play.core.server.NettyServerProvider"

  netty {

    # The default value of the `Server` header to produce if no explicit `Server`-header was included in a response.
    # If this value is the null and no header was included in the request, no `Server` header will be rendered at all.
    server-header = null
    server-header = ${?play.server.server-header}

    # The number of event loop threads. 0 means let Netty decide, which by default will select 2 times the number of
    # available processors.
    eventLoopThreads = 0

    # When Netty shuts down, it ensures that no tasks (requests) are submitted for 'the quiet period' before it finally shuts down.
    # If a task is submitted during the quiet period, it is guaranteed to be accepted and the quiet period will start over.
    #
    # For more details see:
    # https://netty.java.net.cn/4.1/api/io/netty/util/concurrent/EventExecutorGroup.html#shutdownGracefully-long-long-java.util.concurrent.TimeUnit-
    #
    # Play keeps using Netty's default of 2 seconds:
    # https://github.com/netty/netty/blob/netty-4.1.92.Final/common/src/main/java/io/netty/util/concurrent/AbstractEventExecutor.java#L40
    shutdownQuietPeriod = 2 seconds

    # The maximum length of the initial line. This effectively restricts the maximum length of a URL that the server will
    # accept, the initial line consists of the method (3-7 characters), the URL, and the HTTP version (8 characters),
    # including typical whitespace, the maximum URL length will be this number - 18.
    maxInitialLineLength = 4096

    # The maximum length of body bytes that Netty will read into memory at a time.
    # This is used in many ways.  Note that this setting has no relation to HTTP chunked transfer encoding - Netty will
    # read "chunks", that is, byte buffers worth of content at a time and pass it to Play, regardless of whether the body
    # is using HTTP chunked transfer encoding.  A single HTTP chunk could span multiple Netty chunks if it exceeds this.
    # A body that is not HTTP chunked will span multiple Netty chunks if it exceeds this or if no content length is
    # specified. This only controls the maximum length of the Netty chunk byte buffers.
    maxChunkSize = 8192

    # Whether the Netty wire should be logged
    log.wire = false

    # The transport to use, either jdk or native.
    # Native socket transport has higher performance and produces less garbage but are only available on linux 
    transport = "jdk"

    # Netty options. Possible keys here are defined by:
    #
    # https://netty.java.net.cn/4.1/api/io/netty/channel/ChannelOption.html
    # For native socket transport:
    # https://netty.java.net.cn/4.1/api/io/netty/channel/unix/UnixChannelOption.html
    # https://netty.java.net.cn/4.1/api/io/netty/channel/epoll/EpollChannelOption.html
    #
    # Options that pertain to the listening server socket are defined at the top level, options for the sockets associated
    # with received client connections are prefixed with child.*
    option {

      # Set the size of the backlog of TCP connections.  The default and exact meaning of this parameter is JDK specific.
      # SO_BACKLOG = 100

      child {
        # Set whether connections should use TCP keep alive
        # SO_KEEPALIVE = false

        # Set whether the TCP no delay flag is set
        # TCP_NODELAY = false

        # Example how to set native socket transport options
        # (Full qualified class name + "#" + option)
        # "io.netty.channel.unix.UnixChannelOption#SO_REUSEPORT" = true
        # "io.netty.channel.ChannelOption#TCP_FASTOPEN" = 1
      }

    }

  }
}

注意:Netty 服务器后端不是 2.6.x 中的默认后端,因此必须 专门启用

上面的配置特定于 Pekko HTTP 和 Netty 服务器后端,但其他更通用的配置也可用。

# Copyright (C) from 2022 The Play Framework Contributors <https://github.com/playframework>, 2011-2021 Lightbend Inc. <https://www.lightbend.com>

play {

  server {

    # The root directory for the Play server instance. This value can
    # be set by providing a path as the first argument to the Play server
    # launcher script. See `ServerConfig.loadConfiguration`.
    dir = ${?user.dir}

    # HTTP configuration
    http {
      # The HTTP port of the server. Use a value of "disabled" if the server
      # shouldn't bind an HTTP port.
      port = 9000
      port = ${?PLAY_HTTP_PORT}
      port = ${?http.port}

      # The interface address to bind to.
      address = "0.0.0.0"
      address = ${?PLAY_HTTP_ADDRESS}
      address = ${?http.address}

      # The idle timeout for an open connection after which it will be closed
      # Set to null or "infinite" to disable the timeout, but notice that this
      # is not encouraged since timeout are important mechanisms to protect your
      # servers from malicious attacks or programming mistakes.
      idleTimeout = 75 seconds
    }

    # HTTPS configuration
    https {

      # The HTTPS port of the server.
      port = ${?PLAY_HTTPS_PORT}
      port = ${?https.port}

      # The interface address to bind to
      address = "0.0.0.0"
      address = ${?PLAY_HTTPS_ADDRESS}
      address = ${?https.address}

      # The idle timeout for an open connection after which it will be closed
      # Set to null or "infinite" to disable the timeout, but notice that this
      # is not encouraged since timeout are important mechanisms to protect your
      # servers from malicious attacks or programming mistakes.
      idleTimeout = ${play.server.http.idleTimeout}

      # The SSL engine provider
      engineProvider = "play.core.server.ssl.DefaultSSLEngineProvider"
      engineProvider = ${?play.http.sslengineprovider}

      # HTTPS keystore configuration, used by the default SSL engine provider
      keyStore {
        # The path to the keystore
        path = ${?https.keyStore}

        # The type of the keystore
        type = "JKS"
        type = ${?https.keyStoreType}

        # The password for the keystore
        password = ""
        password = ${?https.keyStorePassword}

        # The algorithm to use. If not set, uses the platform default algorithm.
        algorithm = ${?https.keyStoreAlgorithm}
      }

      # HTTPS truststore configuration
      trustStore {

        # If true, does not do CA verification on client side certificates
        noCaVerification = false
      }

      # Whether JSSE want client auth mode should be used. This means, the server
      # will request a client certificate, but won't fail if one isn't provided.
      wantClientAuth = false

      # Whether JSSE need client auth mode should be used. This means, the server
      # will request a client certificate, and will fail and terminate the session
      # if one isn't provided.
      needClientAuth = false
    }

    # The path to the process id file created by the server when it runs.
    # If set to "/dev/null" then no pid file will be created.
    pidfile.path = ${play.server.dir}/RUNNING_PID
    pidfile.path = ${?pidfile.path}

    websocket {
      # Maximum allowable frame payload length. Setting this value to your application's
      # requirement may reduce denial of service attacks using long data frames.
      frame.maxLength = 64k
      frame.maxLength = ${?websocket.frame.maxLength}

      # Periodic keep alive may be implemented using by sending Ping frames
      # upon which the other side is expected to reply with a Pong frame,
      # or by sending a Pong frame, which serves as unidirectional heartbeat.
      # Valid values:
      #   ping - default, for bi-directional ping/pong keep-alive heartbeating
      #   pong - for uni-directional pong keep-alive heartbeating
      periodic-keep-alive-mode = ping

      # Interval for sending periodic keep-alives
      # If a client does not send a frame within this idle time, the server will sent the the keep-alive frame.
      # The frame sent will be the one configured in play.server.websocket.periodic-keep-alive-mode
      # `infinite` by default, or a duration that is the max idle interval after which an keep-alive frame should be sent
      # The value `infinite` means that *no* keep-alive heartbeat will be sent, as: "the allowed idle time is infinite"
      periodic-keep-alive-max-idle = infinite
    }

    debug {
      # If set to true this will attach an attribute to each request containing debug information. If the application
      # fails to load (e.g. due to a compile issue in dev mode), then this configuration value is ignored and the debug
      # information is always attached.
      #
      # Note: This configuration option is not part of Play's public API and is subject to change without the usual
      # deprecation cycle.
      addDebugInfoToRequests = false
    }

    # The maximum length of the HTTP headers. The most common effect of this is a restriction in cookie length, including
    # number of cookies and size of cookie values.
    max-header-size = 8k

    # If a request contains a Content-Length header it will be checked against this maximum value.
    # If the value of a given Content-Length header exceeds this configured value, the request will not be processed
    # further but instead the error handler will be called with Http status code 413 "Entity too large".
    # If set to infinite or if no Content-Length header exists then no check will take place at all
    # and the request will continue to be processed.
    # Play uses the concept of a `BodyParser` to enforce this limit, so we set it to infinite.
    max-content-length = infinite

    # Timeout after which all requests and connections shall be forcefully terminated
    # when shutting down the server. When this timeout gets applied, already the server is not bound to ports
    # and therefore not accepting new connections anymore. It will default to Coordinated Shutdown service-requests-done
    # phase timeout. Because of that default, Play will trigger the timeout 100 milliseconds earlier than actually configured
    # via this config to make sure it fires before the service-requests-done phase ends.
    # Value must be a duration, for example:
    #   play.server.terminationTimeout = 5 seconds
    # This should be less than or equal to the value for `pekko.coordinated-shutdown.phases.service-requests-done.timeout`
    # to prevent early server terminations by the underlying Pekko Coordinated Shutdown system.
    terminationTimeout = null

    # The delay to wait before the server will shut down requests and connections via "graceful" termination. When
    # this delay gets applied, already the server is not bound to ports and therefore not accepting new connections anymore.
    # This config might help you do work around a bug which causes the pekko-http backend to not take response entity streams into account
    # during graceful termination, giving those responses time to finish: https://github.com/akka/akka-http/issues/3209
    # By default, no delay is applied.
    # Value must be a duration, for example:
    #   play.server.waitBeforeTermination = 2 seconds
    # Be aware that `waitBeforeTermination` and `terminationTimeout` both happen within the Coordinated Shutdown `service-requests-done` phase.
    # Therefore, the total value of the two configs should not be longer than the total timeout of the `service-requests-done` phase.
    waitBeforeTermination = 0

    # If body parsing should happen before executing actions defined via action composition (default) or if it should
    # be deferred to a later point in time.
    # Depending on the used Play plugin (PlayScala or PlayJava), setting this config to true will behave slightly differently.
    # Please see the docs for more details:
    # PlayScala
    # https://playframework.com/documentation/latest/ScalaActionsComposition#Action-composition-in-interaction-with-body-parsing
    # PlayJava
    # https://playframework.com/documentation/latest/JavaActionsComposition#Action-composition-in-interaction-with-body-parsing
    deferBodyParsing = false
  }

  editor = ${?PLAY_EDITOR}

}

§日志记录配置

可以通过创建 logback 配置文件来配置日志记录。您的应用程序可以通过以下方式使用它。

§将自定义 logback 配置文件与您的应用程序捆绑在一起

创建一个名为 logback.xml 的备用 logback 配置文件,并将其复制到 <app>/conf

您也可以通过系统属性指定另一个 logback 配置文件。请注意,如果未指定配置文件,则 Play 将在生产模式下使用 Play 附带的默认 logback.xml。这意味着 application.conf 文件中的任何日志级别设置都将被覆盖。作为最佳实践,始终指定您的 logback.xml

§使用 -Dlogger.resource

指定要从类路径加载的另一个 logback 配置文件

$ /path/to/bin/<project-name> -Dlogger.resource=prod-logger.xml

§使用 -Dlogger.file

指定要从文件系统加载的另一个 logback 配置文件

$ /path/to/bin/<project-name> -Dlogger.file=/opt/prod/prod-logger.xml

§使用 -Dlogger.url

指定要从 URL 加载的另一个 logback 配置文件

$ /path/to/bin/<project-name> -Dlogger.url=http://conf.mycompany.com/logger.xml

注意:要查看正在使用的文件,可以设置一个系统属性来调试它:-Dlogback.debug=true

§JVM 配置

您可以将任何 JVM 参数指定给应用程序启动脚本。否则将使用默认的 JVM 设置

$ /path/to/bin/<project-name> -J-Xms128M -J-Xmx512m -J-server

下一步: 设置前端 HTTP 服务器


发现此文档中的错误?此页面的源代码可以在 此处 找到。阅读完 文档指南 后,请随时贡献拉取请求。有疑问或建议要分享?转到 我们的社区论坛 与社区开始对话。