Last active
September 19, 2024 02:43
-
-
Save sebastianwebber/92a3dd4e6b8aa35375409a696a104586 to your computer and use it in GitHub Desktop.
postgres listen/notifiy with golang and `go-pg`
This file contains 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 ( | |
"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 | |
} |
This file contains 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 ( | |
"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