Slick的全称是"Scala Language-Integrated Connection Kit",它是类型安全的函数式关系型映射库,简称FRM
- Functional Relational Mapping。专门用于Scala对关系型数据库的操作。它带来了函数式语言的便利性,可以通过Scala的丰富集合对数据库转换。Slick适用基于Play 和 Akka 框架的功能实现。
Slick底层实现了DBIO
的响应式设计,它是一个Reactive Stream的实现,因此有一下一些特性:
- Clean separation of I/O and CPU-intensive code: Isolating I/O allows you to keep your main thread pool busy with CPU-intensive parts of the application while waiting for I/O in the background.
- Resilience under load(负荷回弹): When a database cannot keep up with the load of your application, Slick will not create more and more threads (thus making the situation worse) or lock out all kinds of I/O. Back-pressure is controlled efficiently through a queue (of configurable size) for database I/O actions, allowing a certain number of requests to build up with very little resource usage and failing immediately once this limit has been reached.
- Reactive Streams for asynchronous streaming.
- Efficient utilization of database resources: Slick can be tuned easily and precisely for the parallelism (number of concurrent active jobs) and resource ussage (number of currently suspended database sessions) of your database server.
Slick 3 的新特性集中在:大量使用组合的设计模式,不需要显式声明session,非阻塞,stream支持的 reactive 等 。
首先创建数据库
1 | DROP TABLE IF EXISTS `action`; |
SBT配置依赖,并加入SBT Task
1 | name := "chapa-Slick" |
建立Dao层
1 | import java.util.concurrent.Executors |
由于使用了HikariCP作为数据库连接池,需要一些额外配置:
1 | db = { |
数据库需要打印输出SQL相关信息,所以加入:
1 | <?xml version="1.0" encoding="UTF-8"?> |
单元测试
1 | import cn.galudisu.fp.models.Tables.profile.api._ |
DAO模式实际上在函数式编程中并不适用,读者有兴趣,可以参考Shapeless的设计进行改造