/
database.go
executable file
·97 lines (83 loc) · 1.85 KB
/
database.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
package monica
import (
"time"
"github.com/DrWrong/monica/config"
"github.com/astaxie/beego/orm"
"github.com/garyburd/redigo/redis"
_ "github.com/go-sql-driver/mysql"
)
var (
// global redis pool
RedisPool *redis.Pool
)
// init beego `orm` config
// monica use beego's orm defaultly
// however we set the `DefaultRowsLimit` to -1 here
// the function read config from `default::mysql` part of yaml file
func InitDb() {
configerMap, _ := config.Map("mysql")
if configerMap == nil {
return
}
orm.DefaultRowsLimit = -1
orm.RegisterDriver("mysql", orm.DRMySQL)
var initOk bool
for key, value := range configerMap {
if key == "default" {
initOk = true
}
valueMap := value.(map[string]interface{})
if err := orm.RegisterDataBase(key, "mysql",
valueMap["dsn"].(string),
valueMap["maxIdle"].(int),
valueMap["maxOpen"].(int),
); err != nil {
panic(err)
}
}
if !initOk {
panic("a database instance called default must be inited")
}
runMode, _ := config.String("runmode")
if runMode == "dev" {
orm.Debug = true
}
}
// init redis
// monica use `redigo` as a redis driver
// this function read config from config file
func InitRedis() {
redisConfig, _ := config.Map("redis")
if redisConfig == nil {
return
}
address := redisConfig["address"].(string)
if address == "" {
panic("redis config not declared: get blank address")
}
db := redisConfig["db"].(int)
RedisPool = &redis.Pool{
MaxIdle: 5,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", address)
if err != nil {
println(err)
return nil, err
}
_, err = c.Do("SELECT", db)
if err != nil {
println(err)
return nil, err
}
return c, nil
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
if err != nil {
println(err)
}
return err
},
}
}