我有一个简单的Main对象,它以这种方式为我的两个服务创建routes:
object GameApp extends App {
val config = ConfigFactory.load()
val host = config.getString("http.host")
val port = config.getInt("http.port")
implicit val system = ActorSystem("game-service")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
val game = new GameRouting
val rate = new RateRouting
val routes: Route = game.route ~ rate.route
Http().bindAndHandle(routes, host, port) map {
binding => println(s"Server start on ${binding.localAddress}")
} recover {
case ex => println(s"Server could not start on ${host}:${port}", ex.getMessage)
}
}现在,我想重构这段代码,并将其移动到单独的方法/类/对象等中:
val game = new GameRouting
val rate = new RateRouting
val routes: Route = game.route ~ rate.route但是这个类(GameRouting和RateRouting)在构造函数中使用了implicit,我不能简单地将这段代码移到不同的地方。我应该如何重构这段代码来获得我想要的东西?
我的另一个问题是- routes类(GameRouting和RateRouting)应该是class还是case class?这是GameRouting类:
trait Protocols extends SprayJsonSupport with DefaultJsonProtocol {
implicit val gameFormat = jsonFormat4(Game)
}
class GameRouting(implicit executionContext: ExecutionContext) extends Protocols {
val gameService = new GameService
val route: Route = {
pathPrefix("games") {
pathEndOrSingleSlash {
get {
complete {
gameService.getGames()
}
} ~
post {
entity(as[Game]) { gameForCreate =>
createGame(gameForCreate)
}
}
} ~
pathPrefix(LongNumber) { id =>
get {
complete {
gameService.getGame(id)
}
} ~ put {
entity(as[Game]) { gameForUpdate =>
complete {
gameService.update(gameForUpdate)
}
}
}
}
}
}
private def createGame(gameForCreate: Game) = {
onComplete(gameService.createGame(gameForCreate)) {
case Success(created) => complete(StatusCodes.Created, created)
case Failure(exception) => complete(StatusCodes.BadRequest, s"An error: $exception")
}
}
}如果我把它设为case,我就不能从Main对象访问字段routes。如何解决这个问题,或者以更好的方式编写它?也许有一些基本的问题,但几周来我一直在学习Scala和Akka。
发布于 2018-12-23 05:59:43
您只需将您的隐式对象移动到单独的对象:
object GameAppImplicits {
implicit val system = ActorSystem("game-service")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
}然后在需要时导入:
import yourpackage.GameAppImplicits._对于您的第二个问题,case类通常用于建模不可变的数据。在这种情况下,您并不真正需要任何功能,case类为您提供了(如automatic toString、equals、copy等),因此我认为最好只使用普通class。
https://stackoverflow.com/questions/53899175
复制相似问题