11. PostgreSQL: Β Listen/Notify
11ΠΠΈΡ Π°ΠΈΠ» Β Π‘Π°Π»ΠΎΡΠΈΠ½. Β ΠΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠ΅ Β Go Π² Β Π±ΡΠΊΠ΅Π½Π΄Π΅ ΠΏΡΠΈΠ»ΠΎΠΆΠ΅Π½ΠΈΡ Β Π‘ΠΌΠΎΡΡΠΈ+
CREATE OR REPLACE FUNCTION data_updated() RETURNS trigger AS $$
BEGIN
IF TG_OP = 'INSERT' OR OLD <> NEW THEN
PERFORM pg_notify('data_updates', TG_TABLE_NAME || ' ' ||
NEW.id);
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER on_season_update
AFTER INSERT OR UPDATE
ON seasons
FOR EACH ROW
EXECUTE PROCEDURE data_updated();
12. PostgreSQL: Β Listen/Notify
func ListenForDataUpdates(config *utils.DbConfig) (*utils.Fanout, error) {
f := utils.NewFanout()
l := pq.NewListener("user=smotri-api dbname=smotri", 50*time.Millisecond, 10*time.Second)
err := l.Listen("data_updates")
err = l.Ping()
go func() {
pingTicker := time.Tick(15 * time.Second)
for {
var n *pq.Notification
select {
case t := <-pingTicker:
un := t.UnixNano()
logger.Printf("data_updates: ping %d", un)
f.Publish(un)
continue
case n = <-l.Notify:
if n == nil {
logger.Printf("data_updates: reconnected")
continue
}
}
...
f.Publish(str)
}
}
return f, nil
}
12