2016-11-29 76 views
0

我有一個使用play 2.5框架開發的寧靜的網絡服務。 我想通過調用自己來啓動我的Web服務。這是爲了確保我的服務完全正常運行。播放2.5啓動網絡服務

我採取的方法是使用eagerBinding。但是類中的代碼使用注入的渴望結合被執行之前的應用程序啓動

這裏是我的eagerbinding代碼看起來像

@Singleton 
class PrimingMe @Inject()(ws: WSClient) { 

    isServicePrimed 

    def isServicePrimed: Boolean = { 

    println("PRIME ME!!!") 
    val response = ws.url("http://localhost:9000/index").get 
     .map { 
     response => 
      response.status match { 
      case 200 => true 
      case _ => false 
      } 
     } 

    try { 
     Await.result(response, 5.second) 
    } catch { 
     case _ => false 
    } 

    } 

} 


class ServiceInjectionModule extends AbstractModule { 

    def configure(): Unit = { 

    bind(classOf[PrimingMe]).asEagerSingleton 
    } 
} 

內application.conf

play.modules.enabled += "util.ServiceInjectionModule" 

我想用虛擬服務調用來填充我的應用程序,這樣當真正的流量開始時,所有的數據庫連接都會被創建。目前,我對服務的第一個API調用比平時花費的時間長得多。我還有什麼其他選擇可以實現這一點。

回答

2

否目的不被擊敗。急切的加載仍然按預期工作。

確保util.ServiceInjectionModule是第一個通過在application.conf文件的頂部聲明加載的模塊。

我已經看到了你的問題,以證明後做了一個小實驗這個

這是我模塊的樣子。它是在根目錄申報和模塊是根主任即應用程序,您不必明確添加到application.conf

class Module extends AbstractModule { 
    override def configure() = { 
    //It is very important for this call to be on the top. 
    bind(classOf[Initialize]).asEagerSingleton() 
    } 
} 

渴望單身

import com.google.inject.Inject 
import com.google.inject.Singleton 
import play.api.Logger 
import play.api.libs.ws.WSClient 

import scala.concurrent.Await 
import scala.concurrent.duration.Duration 

@Singleton 
class Initialize @Inject() (wsClient: WSClient) { 

    hit() 

    def hit(): Unit = { 
    val f = wsClient.url("http://www.google.com").get() 
    val result = Await.result(f, Duration.Inf) 
    Logger.info(s"status: ${result.status}") 
    } 
} 

輸出:

[info] application - status: 200 
[info] play.api.Play - Application started (Dev) 

從上面的輸出中可以看到Module已經加載並調用了hit()

+0

爲什麼它必須是第一個模塊? – rethab

+0

@rethab以防萬一初始化順序很重要... – pamu

+0

這是正確的工作,我不得不開始我的應用程序與sbt編譯開始。然而問題是我不能在服務開始之前就打電話給'我自己'。讓我重述一下這個問題。 – konquestor