-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexpress.go
113 lines (86 loc) · 2.23 KB
/
express.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
111
112
113
// Copyright 2014 The dbrouter Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package dbrouter
import (
"fmt"
//"sync"
"regexp"
)
type clsEntry struct {
// express to instances
full map[string]*dbExpress
regex map[string]*dbExpress
}
// 没有考虑同步问题
// 目前只支持初始化一次加载完成
// 构建完成后不能动态调整
type dbCluster struct {
// cluster to express
clusters map[string]*clsEntry
// cache table to instance
// map[string]string
//locCache map[string]string
}
type dbExpress struct {
lookup *dbLookupCfg
reg *regexp.Regexp
}
func (m *dbExpress) String() string {
return fmt.Sprintf("look:%s reg:%s", m.lookup, m.reg)
}
func (m *dbCluster) addInstance(cluster string, lcfg *dbLookupCfg) error {
if _, ok := m.clusters[cluster]; !ok {
m.clusters[cluster] = &clsEntry {
full: make(map[string]*dbExpress),
regex: make(map[string]*dbExpress),
}
}
match := lcfg.Match
if match == "full" {
if m.clusters[cluster].full[lcfg.Express] != nil {
return fmt.Errorf("dup match full in cluster:%s express:%s", cluster, lcfg.Express)
}
m.clusters[cluster].full[lcfg.Express] = &dbExpress{lookup: lcfg}
} else if match == "regex" {
if m.clusters[cluster].regex[lcfg.Express] != nil {
return fmt.Errorf("dup match regex in cluster:%s express:%s", cluster, lcfg.Express)
}
reg, err := regexp.CompilePOSIX(lcfg.Express)
if err != nil {
return err
}
m.clusters[cluster].regex[lcfg.Express] = &dbExpress{lookup: lcfg, reg: reg}
} else {
return fmt.Errorf("match type:%s not support", match)
}
return nil
}
func (m *dbCluster) getLookup(cluster string, table string) *dbLookupCfg {
exp := m.clusters[cluster]
if exp == nil {
return nil
}
// 先全匹配查找
en := exp.full[table]
if en != nil {
return en.lookup
}
// 正则
for _, e := range exp.regex {
// 必须全部匹配上
f := e.reg.FindString(table)
//fmt.Println("DDDDDD", f, table, e)
if table == f {
return e.lookup
}
}
return nil
}
func (m *dbCluster) getInstance(cluster string, table string) string {
if lk := m.getLookup(cluster, table); lk != nil {
return lk.Instance
} else {
return ""
}
}