Created
January 21, 2017 15:26
-
-
Save ik5/ad9783afd50e0b769f2386e8faaea427 to your computer and use it in GitHub Desktop.
Listen to a Pg event in go
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
package main | |
import ( | |
"database/sql" | |
"fmt" | |
"time" | |
"github.com/lib/pq" | |
) | |
func waitForNotification(l *pq.Listener) { | |
for { | |
select { | |
case ch := <-l.Notify: | |
fmt.Printf("received notification, new cdr available %#v\n", ch) | |
return | |
case <-time.After(90 * time.Second): | |
go func() { | |
l.Ping() | |
}() | |
// Check if there's more work available, just in case it takes | |
// a while for the Listener to notice connection loss and | |
// reconnect. | |
// fmt.Println("received no work for 90 seconds, checking for new work") | |
return | |
} | |
} | |
} | |
func reportProblem(ev pq.ListenerEventType, err error) { | |
fmt.Printf("%+v, err: %s", ev, err) | |
} | |
func main() { | |
conninfo := "host=localhost user=postgres dbname=tts sslmode=disable" | |
db, err := sql.Open("postgres", conninfo) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(db, conninfo) | |
reportProblem := func(ev pq.ListenerEventType, err error) { | |
if err != nil { | |
fmt.Println(err.Error()) | |
} | |
} | |
listener := pq.NewListener(conninfo, 10*time.Second, time.Minute, reportProblem) | |
err = listener.Listen("cdr_created") | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("entering main loop") | |
for { | |
// process all available work before waiting for notifications | |
//getWork(db) | |
waitForNotification(listener) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment