我正在嘗試按照檔案中的說明設定一個簡單的 akka-grpc 服務器。
migrationResult match {
case Left(exception) => system.log.error(exception, "Exception while migrating schema", exception)
case Right(_) =>
system.log.info(s"Schema migrated with success")
val registerService: HttpRequest => Future[HttpResponse] =
RegisterServiceHandler(new RegisterImpl())
Http().newServerAt(interface = "0.0.0.0", port = port).bind(registerService)
}
問題是它運行后立即停止,它不聽任何電話。服務實作 ( RegisterImpl) 看起來像這樣
class RegisterImpl(implicit mat: Materializer) extends RegisterService with LazyLogging {
import mat.executionContext
override def registerUser(request: RegisterRequest): Future[RegisterResponse] = {
val credentials = UserCredentials(UUID.randomUUID(), request.username, request.emailAddress, request.password)
val user = User(None, request.fullName, request.city, request.address, request.neighborhood, credentials)
val responseIO = for {
_ <- userRepository.insertUser(user)
} yield ()
responseIO.attempt.unsafeRunSync() match {
case Right(_) =>
Future.successful(new RegisterResponse(true))
case Left(e) =>
logger.error(s"User registration failed because of error: ${e.getMessage}")
Future.successful(new RegisterResponse(false))
}
}
uj5u.com熱心網友回復:
我懷疑你的阻塞代碼(使用runUnsafeSync,同步映射Either到Future)是它的罪魁禍首。
// This is blocking current thread
responseIO.attempt.unsafeRunSync() match {
// These 2 create Futures, but only after blocking is released
// by the finished IO computation (if it finishes...)
case Right(_) =>
Future.successful(new RegisterResponse(true))
case Left(e) =>
logger.error(s"User registration failed because of error: ${e.getMessage}")
Future.successful(new RegisterResponse(false))
}
// You'd have to use
// Future { blocking { ... } }
// instead of match Future.successful to be async
// (and inform Future's thread pool that you are blocking)
// (but it still could lead to a deadlock or worse performance).
有幾種方法可以處理它(使用Future { ... }with blocking,除錯執行緒池),但我建議將您的服務實作為:
responseIO.attempt.map {
case Right(_) =>
new RegisterResponse(true)
case Left(e) =>
logger.error(s"User registration failed because of error: ${e.getMessage}")
new RegisterResponse(false)
}.unsafeToFuture // IO knows how to create a Future without issues
確保轉換Future為由IO自身處理而不會產生不必要的阻塞。
uj5u.com熱心網友回復:
似乎問題與 sbt 有關,而不與 akka 或實作有關,我剛剛將 sbt 版本從 build.properties 從 更改1.6.1為1.5.2,仍然不確定新版本出了什么問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/401915.html
