-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmysql.go
90 lines (78 loc) · 2.32 KB
/
mysql.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
package xmysql
import (
"errors"
"sync"
"time"
)
type MysqlProxy struct {
mux sync.RWMutex
mysqlConnPool map[string]*MysqlConn
}
var (
GMysqlProxy = &MysqlProxy{
mysqlConnPool: make(map[string]*MysqlConn),
}
DEFAULT_PING_PERIOD = 5 * time.Second
)
/*
* master_addr: user:passwd@tcp(address:port)/database
* backup_addr: user1:passwd1@tcp(address1:port1)/db1|weight1;user2:passwd2@tcp(address2:port2)/db2|weight
*/
func RegisterMysqlService(service string, master_addr, backup_addr string) error {
mysql_conn, err := RegisterMysql(master_addr, backup_addr)
if err != nil {
return err
}
GMysqlProxy.mux.Lock()
GMysqlProxy.mysqlConnPool[service] = mysql_conn
GMysqlProxy.mux.Unlock()
return nil
}
func SetHealthCheckPeriod(period int) {
DEFAULT_PING_PERIOD = time.Duration(period) * time.Second
}
func Insert(service string, sql string, args ...interface{}) (lastInsertId int64, err error) {
GMysqlProxy.mux.RLock()
defer GMysqlProxy.mux.RUnlock()
if conn, ok := GMysqlProxy.mysqlConnPool[service]; ok {
return conn.Insert(sql, args...)
}
err = errors.New("not found db instance")
return
}
func Update(service string, sql string, args ...interface{}) (rowsAffected int64, err error) {
GMysqlProxy.mux.RLock()
defer GMysqlProxy.mux.RUnlock()
if conn, ok := GMysqlProxy.mysqlConnPool[service]; ok {
return conn.Update(sql, args...)
}
err = errors.New("not found db instance")
return
}
func Delete(service string, sql string, args ...interface{}) (rowsAffected int64, err error) {
GMysqlProxy.mux.RLock()
defer GMysqlProxy.mux.RUnlock()
if conn, ok := GMysqlProxy.mysqlConnPool[service]; ok {
return conn.Delete(sql, args...)
}
err = errors.New("not found db instance")
return
}
func Select(service string, sql string, args ...interface{}) (result []map[string]string, err error) {
GMysqlProxy.mux.RLock()
defer GMysqlProxy.mux.RUnlock()
if conn, ok := GMysqlProxy.mysqlConnPool[service]; ok {
return conn.Select(sql, args...)
}
err = errors.New("not found db instance")
return
}
func QueryWithCb(sqlFunc RowScanCallback, service string, sql string, args ...interface{}) (err error) {
GMysqlProxy.mux.RLock()
defer GMysqlProxy.mux.RUnlock()
if conn, ok := GMysqlProxy.mysqlConnPool[service]; ok {
return conn.QueryWithCb(sqlFunc, sql, args...)
}
err = errors.New("not found db instance")
return
}