§將 Play 伺服器嵌入應用程式
儘管 Play 應用程式最常作為其自己的容器,您也可以將 Play 伺服器嵌入您現有的應用程式中。這可以與 Twirl 範本編譯器和 Play 路由編譯器結合使用,但當然不是必要的,嵌入 Play 應用程式的常見用例是因為您只有少數幾個非常簡單的路由。
啟動嵌入式 Play 伺服器的最簡單方法是使用 Server
工廠方法。如果您只需要提供一些直接的路由,您可以決定使用 路由 DSL,因此您需要以下匯入
import play.routing.RoutingDsl;
import play.server.Server;
import static play.mvc.Controller.*;
然後你可以使用 forRouter
方法建立一個伺服器
Server server =
Server.forRouter(
(components) ->
RoutingDsl.fromComponents(components)
.GET("/hello/:to")
.routingTo((request, to) -> ok("Hello " + to))
.build());
預設情況下,這會在測試模式下於一個隨機埠啟動一個伺服器。你可以使用 httpPort
方法檢查埠
CompletionStage<WSResponse> response =
ws.url("https://127.0.0.1:" + server.httpPort() + "/hello/world").get();
你可以透過傳入一個 port
和/或 mode
來設定伺服器
Server server =
Server.forRouter(
(components) ->
RoutingDsl.fromComponents(components)
.GET("/hello/:to")
.routingTo((request, to) -> ok("Hello " + to))
.build());
要停止你已經啟動的伺服器,只需呼叫 stop
方法
server.stop();
注意:Play 需要設定一個 應用程式密碼 才能啟動。這可以透過在你的應用程式中提供一個
application.conf
檔案,或使用play.http.secret.key
系統屬性來設定。
在這個文件當中發現錯誤了嗎?這個頁面的原始碼可以在 這裡 找到。在閱讀完 文件指南 之後,請隨時提交一個 pull request。有問題或建議要分享嗎?請到 我們的社群論壇 與社群開始對話。