Skip to content

Instantly share code, notes, and snippets.

@sebastianwebber
Last active September 19, 2024 02:43
Show Gist options
  • Save sebastianwebber/92a3dd4e6b8aa35375409a696a104586 to your computer and use it in GitHub Desktop.
Save sebastianwebber/92a3dd4e6b8aa35375409a696a104586 to your computer and use it in GitHub Desktop.
postgres listen/notifiy with golang and `go-pg`
package main
import (
"log"
"time"
"github.com/go-pg/pg"
)
const maxWorkers = 5
var (
limiter = make(chan int, maxWorkers)
)
func main() {
db := pg.Connect(&pg.Options{
User: "seba",
ApplicationName: "test_notify",
})
ln := db.Listen("mychan")
defer ln.Close()
ch := ln.Channel()
for notifyOutput := range ch {
limiter <- 1
go processMessage(notifyOutput.Payload)
}
}
func processMessage(message string) {
log.Printf("[ %d / %d ] added to queue: %s\n", cap(limiter), maxWorkers, message)
time.Sleep(1 * time.Second)
<-limiter
}
package main
import (
"log"
"github.com/go-pg/pg"
)
func main() {
db := pg.Connect(&pg.Options{
User: "seba",
ApplicationName: "test_notify",
})
ln := db.Listen("mychan")
defer ln.Close()
ch := ln.Channel()
for val := range ch {
processMessage(val.Payload)
}
}
func processMessage(message string) {
log.Println("received message:", message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment