playframework - jdbc

接着上一篇的play framework redis緩存、作爲一個優秀的框架怎麼沒有數據庫操作呢、這篇介紹一下怎麼配置jdbc連接、使用的數據庫是mysql。

使用教程

build.sbt 添加依賴

libraryDependencies += javaJdbc
libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.47"

jdbc配置

db {
  default.driver = com.mysql.jdbc.Driver
  default.url = "jdbc:mysql://localhost:3306/testdb?characterEncoding=UTF-8&useSSL=false"
  default.username = root
  default.password = root
  default.logSql = true
}

控制器注入使用

@Singleton
class HomeController @Inject()(@NamedDatabase("default") db: Database, cc: ControllerComponents)(implicit assetsFinder: AssetsFinder)
  extends AbstractController(cc) {

  def index = Action {
    val res = new mutable.ListBuffer[String]()
    db.withConnection {
      conn =>
        val state = conn.createStatement()
        val result = state.executeQuery("select * from user")
        while (result.next()) {
          res += result.getString("nickName")
        }
    }
    Ok(views.html.index(res.mkString(",")))
  }

}

刷新頁面就可以看到啦

image

連接池配置

play.db {
  # The combination of these two settings results in "db.default" as the
  # default JDBC pool:
  config = "db"
  default = "default"

  # Play uses HikariCP as the default connection pool.  You can override
  # settings by changing the prototype:
  prototype {
    # Sets a fixed JDBC connection pool size of 50
    hikaricp.minimumIdle = 50
    hikaricp.maximumPoolSize = 50
  }
}

默認初始50個連接

驗證mysql是不是

root@385ff263e2bd:/# mysqladmin -uroot -proot status
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Uptime: 6053  Threads: 51  Questions: 2898  Slow queries: 0  Opens: 569  Flush tables: 1  Open tables: 384  Queries per second avg: 0.478

可以看到Threads:是51個、有一個連接是其它項目的。

最後

play framework真的很好用、添加代碼動態加載。真的很棒。
下一篇文章繼續介紹在playframework中如何上傳文件。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章