CodeRoadMap
首页路线题库资源库文章社区
CodeRoadMap

程序员的学习成长路线图。内容免费开放,登录后可同步路线图与课时进度。

由 程序员柏风 独立维护 · 关于作者

学习

  • 路线图
  • 课程
  • 面试题
  • 文章
  • 我

更多

  • 资源
  • 社区
  • 关于作者
  • 内容说明

© 2026 CodeRoadMap

津ICP备2026012044号-1·津公网安备12011002026155号·coderoadmap@126.com
Scala 语言入门/课时/后端框架
RawBlame
课时目录12 节

Scala 语言入门

  1. 01Scala 是什么
  2. 02基础语法
  3. 03OOP 与模式匹配
  4. 04集合与高阶函数
  5. 05函数式编程
  6. 06类型系统
  7. 07构建工具
  8. 08后端框架
  9. 09数据与 JSON
  10. 10测试
  11. 11并发与流
  12. 12综合练习

后端框架

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 PekkoActor + Streams高并发、事件驱动、微服务
PlayMVC + 异步传统企业 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 思路不同。

与 Java 对照

Scala 后端Java 对照
Pekko Actor无内置;Virtual Thread + 消息队列
Play ControllerSpring @RestController
http4s routesJAX-RS / Spring WebFlux Router
ZIO LayerSpring @Configuration + DI

Spring Boot 仍是 CodeRoadMap 主栈;Scala 框架适合高并发、FP 团队或 Spark 周边服务。

练习

  • 用 Pekko HTTP 或 Play 添加 GET /api/bookmarks/:id
  • 对比同一 health 端点在 Spring Boot 中的代码量
  • 在 /roadmaps/scala 标记 Backend 节点

小结

Pekko 管并发、Play 管全栈、http4s/ZIO 管类型安全 FP API。 下一课数据与 JSON。见 scala-essentials。

加载本节练习…
← 上一课构建工具下一课 →数据与 JSON