/
morestore.go
70 lines (57 loc) · 1.39 KB
/
morestore.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
package main
import (
"github.com/mikejs/gomongo/mongo"
"redis"
"os"
"fmt"
)
type Context struct {
redisClient redis.Client
mongoPool chan *mongo.Collection
mongoAddr string
mongoDb string
}
func (c *Context) popMongoCollection() (*mongo.Collection, os.Error) {
collection := <- c.mongoPool
if collection == nil {
conn, err := mongo.Connect(c.mongoAddr)
if err != nil {
return nil, err
}
collection = conn.GetDB(c.mongoDb).GetCollection("logs")
}
return collection, nil
}
/*
* TODO: add dropped connection detection.
*/
func (c *Context) pushMongoCollection(collection *mongo.Collection) {
c.mongoPool <- collection
}
func (c *Context) Update(stat *Statmsg) {
_, err := c.redisClient.Incr("hit:" + stat.Key)
if err != nil {
fmt.Printf("Error from redis: %s\n", err.String())
}
collection, err := c.popMongoCollection()
if err != nil {
fmt.Printf("Error from mongo: %s\n", err.String())
}
doc, _ := mongo.Marshal(stat)
collection.Insert(doc)
c.pushMongoCollection(collection)
}
func Setup(mongoAddr string, mongoDb string,
redisAddr string, redisDb int, poolSize int) (c *Context) {
c = new(Context)
c.redisClient.Addr = redisAddr
c.redisClient.Db = redisDb
c.redisClient.MaxPoolSize = poolSize
c.mongoPool = make(chan *mongo.Collection, poolSize)
for i := 0; i < poolSize; i++ {
c.mongoPool <- nil
}
c.mongoAddr = mongoAddr
c.mongoDb = mongoDb
return c
}