gpt4 book ai didi

clojure - Clojure 中的连接池

转载 作者:行者123 更新时间:2023-12-04 01:14:16 24 4
gpt4 key购买 nike

我无法理解pool-dbconnection 函数的使用在这个connection pooling guide .

(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)"])

为什么我们不能简单地做?

(def connection (get-pool db-spec))

; usage in code
(jdbc/query connection ["SELECT SUM(1, 2, 3)"])

最佳答案

延迟确保您在第一次尝试使用它时创建连接池,而不是在加载命名空间时。

这是一个好主意,因为您的连接池可能由于多种原因中的任何一种而无法创建,并且如果它在 namespace 加载期间失败,您将得到一些奇怪的行为 - 连接池创建失败后的任何 defs 都不会例如,进行评估。

一般来说,顶级 var 定义应该构造成它们不会在运行时失败。

请记住,它们也可能在 AOT 编译过程中进行评估,如下面的 amalloy 说明。

关于clojure - Clojure 中的连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54613947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com