/
bare_minimum_pg_notify_redis_pub.go
71 lines (58 loc) · 1.6 KB
/
bare_minimum_pg_notify_redis_pub.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
This one is just to have a comparision to anothre bare minimum code.
*/
package main
import (
"encoding/json"
"fmt"
"os"
"regexp"
"time"
"io/ioutil"
"github.com/garyburd/redigo/redis"
"github.com/lib/pq"
"gopkg.in/yaml.v2"
)
type DBCluster struct {
Password string
Parition map[string]struct {
Write struct {
Name string
IP string
}
} `yaml:",inline"`
}
func publish(redisdb redis.Conn, payload []string) {
m := make(map[string]string)
for k, v := range []string{"id", "account_id", "action_type", "referrer_type", "contract_id", "payment_id", "amount", "balance_after"} {
m[v] = payload[k]
}
jsonVal, _ := json.Marshal(m)
msg := string(jsonVal)
redisdb.Do("PUBLISH", "balance_"+m["account_id"], msg)
redisdb.Do("PUBLISH", m["action_type"]+"_"+m["account_id"], msg)
}
func waitForNotification(dbcluter DBCluster, parition string) {
conninfo := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=require", "read", dbcluter.Password, dbcluter.Parition[parition].Write.IP, "regentmarkets")
listener := pq.NewListener(conninfo, 5*time.Second, 10*time.Second, nil)
_ = listener.Listen("transactions_watcher")
redisdb, _ := redis.DialURL(os.Getenv("REDIS_URL"))
var notification *pq.Notification
for {
select {
case notification = <-listener.Notify:
if notification != nil {
publish(redisdb, regexp.MustCompile(",").Split(notification.Extra, -1))
}
}
}
}
func main() {
var dbcluster DBCluster
source, _ := ioutil.ReadFile("db.yml")
yaml.Unmarshal(source, &dbcluster)
for parition, _ := range dbcluster.Parition {
go waitForNotification(dbcluster, parition)
}
select {}
}