-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository.go
110 lines (83 loc) · 2.07 KB
/
repository.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gomodule/redigo/redis"
)
type MatchRepo interface {
Get(string) (*Match, error)
Save(*Match)
GetWaitingMatch() (*Match, error)
AddWaitingMatch(*Match)
Lock(id string) error
}
type RedisRepo struct {
connPool *redis.Pool
}
func newMatchRepo(connPool *redis.Pool) MatchRepo {
mr := RedisRepo{connPool: connPool}
return &mr
}
func (r *RedisRepo) Get(id string) (*Match, error) {
conn := r.connPool.Get()
defer conn.Close()
matchKey := fmt.Sprintf("match:%v", id)
matchStr, err := redis.String(conn.Do("GET", matchKey))
if err != nil {
return nil, err
}
m := Match{}
err = json.Unmarshal([]byte(matchStr), &m)
return &m, err
}
func (r *RedisRepo) GetWaitingMatch() (*Match, error) {
conn := r.connPool.Get()
defer conn.Close()
mId, err := redis.String(conn.Do("SPOP", "waiting_match"))
if err != nil {
log.Print("no waiting match - ", err)
return nil, err
}
return r.Get(mId)
}
func (r *RedisRepo) AddWaitingMatch(m *Match) {
matchKey := fmt.Sprintf("match:%v", m.Id)
matchValue, err := json.Marshal(m)
checkFatalError(err)
conn := r.connPool.Get()
defer conn.Close()
err = conn.Send("MULTI")
checkFatalError(err)
err = conn.Send("SET", matchKey, matchValue)
checkFatalError(err)
err = conn.Send("SADD", "waiting_match", m.Id)
checkFatalError(err)
_, err = conn.Do("EXEC")
checkFatalError(err)
}
func (r *RedisRepo) Save(m *Match) {
matchKey := fmt.Sprintf("match:%v", m.Id)
matchValue, err := json.Marshal(m)
checkFatalError(err)
conn := r.connPool.Get()
defer conn.Close()
_, err = conn.Do("SET", matchKey, matchValue)
checkFatalError(err)
}
//I know this will not work well on a distributed Redis
// see: https://redis.io/topics/distlock
func (r *RedisRepo) Lock(id string) error {
conn := r.connPool.Get()
defer conn.Close()
_, err := conn.Do("SET", id, "locked", "EX", 1, "NX")
return err
}
//Better handling needed, but no time.
//http server on main.go will handle it and send a 500
func checkFatalError(err error) {
if err != nil {
log.Println(err)
panic(err)
}
}