Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Postgres listen/notify in Clojure using http://impossibl.github.io/pgjdbc-ng/
; Postgres listen/notify in Clojure using http://impossibl.github.io/pgjdbc-ng/
; in project.clj dependencies
; [com.impossibl.pgjdbc-ng/pgjdbc-ng "0.5"]
(ns pglisten.core
(:import [com.impossibl.postgres.jdbc PGDataSource]
[com.impossibl.postgres.api.jdbc PGNotificationListener]))
(def datasource (doto (PGDataSource.)
(.setHost "localhost") ; todo move into
(.setPort 5432)
(.setDatabase "listenpg_db")
(.setUser "listenpg_user")
(.setPassword "password")))
; create a listener that triggers when a message is received
(def listener
(reify PGNotificationListener
(^void notification [this ^int processId ^String channelName ^String payload]
(println "msg: " payload) )))
; setup a connection with the listener
(def connection
(doto (.getConnection datasource)
(.addNotificationListener listener)))
; begin listening to a channel
(doto (.createStatement connection)
(.execute "LISTEN mymessages;")
(.close))
; trigger message using psql, should print to console in clojure app.
; select pg_notify('mymessages', 'hello...');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment