Skip to content

Instantly share code, notes, and snippets.

@niwinz
Forked from mikeball/core.clj
Created November 25, 2016 11:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niwinz/be0fe08263fd716fa2032ad590f220be to your computer and use it in GitHub Desktop.
Save niwinz/be0fe08263fd716fa2032ad590f220be to your computer and use it in GitHub Desktop.
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