后端框架
Akka/Pekko、Play、http4s、ZIO。
35 分钟
后端框架
Scala 后端生态丰富:Akka / Apache Pekko(Actor)、Play(全栈 MVC)、http4s(函数式 HTTP)、ZIO(效应系统)。对照 /roadmaps/scala「Backend Frameworks」节点。
学习目标
- 了解 Actor 模型与 Pekko HTTP 基本路由
- 对照 Play、http4s、ZIO HTTP 的选型场景
- 读懂最小 REST 端点示例
核心概念
框架选型
| 框架 | 风格 | 典型场景 |
|---|---|---|
| Apache Pekko | Actor + Streams | 高并发、事件驱动、微服务 |
| Play | MVC + 异步 | 传统企业 Web、全栈 |
| http4s | 纯函数式 HTTP | 类型安全 API、Cats 生态 |
| ZIO HTTP | 效应 + 组合 | 现代 FP 后端、可测试性 |
Pekko 是 Akka 的开源分支(Apache 基金会);新项目可优先关注 Pekko 与 ZIO。
Pekko HTTP 路由示例
import scala.concurrent.ExecutionContext
import org.apache.pekko.actor.typed.{ActorSystem, Behaviors}
import org.apache.pekko.http.scaladsl.Http
import org.apache.pekko.http.scaladsl.model._
import org.apache.pekko.http.scaladsl.server.Directives._
case class Bookmark(id: Long, url: String, title: String)
@main def server(): Unit =
given system: ActorSystem[Nothing] = ActorSystem(Behaviors.empty, "api")
given ec: ExecutionContext = system.executionContext
val routes =
path("health") {
get { complete("ok") }
} ~
path("api" / "bookmarks") {
get {
complete(StatusCodes.OK, List(Bookmark(1, "https://a.com", "A")).toString)
} ~
post {
entity(as[String]) { body =>
complete(StatusCodes.Created, s"created: $body")
}
}
}
Http().newServerAt("localhost", 8080).bind(routes)
println("Server at http://localhost:8080")
~ 组合路由;Directives 提供声明式 HTTP 匹配,类似 Spring @GetMapping 但嵌套 DSL。
效应风格(概念)
// ZIO 伪代码风格 — 强调 composable 效应
def getBookmark(id: Long): ZIO[Any, Throwable, Bookmark] =
for
_ <- ZIO.logInfo(s"fetch $id")
b <- ZIO.attempt(fetchFromDb(id))
yield b
ZIO / Cats Effect 用 IO/ZIO 描述副作用,编译期追踪错误与依赖;与 Spring 命令式 Controller 思路不同。