我无法理解本连接池指南中的使用pool-db和功能。connection
(defn- get-pool
"Creates Database connection pool to be used in queries"
[{:keys [host-port db-name username password]}]
(let [pool (doto (ComboPooledDataSource.)
(.setDriverClass "com.mysql.cj.jdbc.Driver")
(.setJdbcUrl (str "jdbc:mysql://"
host-port
"/" db-name))
(.setUser username)
(.setPassword password)
;; expire excess connections after 30 minutes of inactivity:
(.setMaxIdleTimeExcessConnections (* 30 60))
;; expire connections after 3 hours of inactivity:
(.setMaxIdleTime (* 3 60 60)))]
{:datasource pool}))
(def pool-db (delay (get-pool db-spec)))
(defn connection [] @pool-db)
; usage in code
(jdbc/query (connection) ["Select SUM(1, 2, 3)"])
Run Code Online (Sandbox Code Playgroud)
为什么我们不能简单地做呢?
(def connection (get-pool db-spec))
; usage in code
(jdbc/query connection ["SELECT SUM(1, 2, 3)"])
Run Code Online (Sandbox Code Playgroud)
延迟可确保您在第一次尝试使用连接池时创建连接池,而不是在加载命名空间时创建连接池。
这是一个好主意,因为您的连接池可能由于多种原因之一而无法创建,如果在名称空间加载期间失败,您将得到一些奇怪的行为 - 创建失败的连接池后的任何定义都不会被评估,例如。
一般来说,应该构建顶级 var 定义,这样它们就不会在运行时失败。
请记住,它们也可能在 AOT 编译过程中进行评估,如下面的 amalloy 注释。