Last active
September 27, 2015 09:18
-
-
Save zkat/1247190 to your computer and use it in GitHub Desktop.
pomo connection reuse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;;; | |
| ;;; Connection pooling | |
| ;;; | |
| (defparameter *connection-pool-lock* (bt:make-lock)) | |
| (defparameter *max-pooled-connections* 50) | |
| (defvar *connection-pool* (make-queue *max-pooled-connections*)) | |
| (defun get-connection () | |
| (or (bt:with-lock-held (*connection-pool-lock*) | |
| (unless (queue-empty-p *connection-pool*) | |
| (dequeue *connection-pool*))) | |
| (apply #'connect (list *db-name* *db-user* *db-password* *db-host*)))) | |
| (defun done-with-connection (connection) | |
| (bt:with-lock-held (*connection-pool-lock*) | |
| (if (queue-full-p *connection-pool*) | |
| (disconnect connection) | |
| (enqueue connection *connection-pool*)))) | |
| (defun clear-pooled-connections () | |
| (bt:with-lock-held (*connection-pool-lock*) | |
| (loop until (queue-empty-p *connection-pool*) | |
| for connection = (dequeue *connection-pool*) | |
| when (connected-p connection) | |
| do (disconnect connection)))) | |
| (defmacro with-db ((&key (reusep t)) &body body) | |
| `(let* ((reusing-connection-p (and *database* ,reusep)) | |
| (*database* (or (when reusing-connection-p *database*) | |
| (get-connection)))) | |
| (unwind-protect (progn ,@body) | |
| (unless reusing-connection-p | |
| (done-with-connection *database*))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment