-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcachefactory.go
More file actions
77 lines (67 loc) · 1.95 KB
/
Copy pathcachefactory.go
File metadata and controls
77 lines (67 loc) · 1.95 KB
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
package sop
import (
"fmt"
"net/url"
"strconv"
"strings"
"sync"
)
// L2CacheType defines the type of cache to use.
type L2CacheType int
const (
// Default represents no (L2) caching.
NoCache L2CacheType = iota
// InMemory represents an in-memory cache.
InMemory
// Redis represents a Redis cache.
Redis
)
// L2CacheFactory defines the function signature for creating a cache client.
type L2CacheFactory func(TransactionOptions) L2Cache
var cacheRegistry = make(map[L2CacheType]L2CacheFactory)
var cacheInstances = make(map[string]L2Cache)
var l2locker sync.Mutex
// RegisterL2CacheFactory registers a cache factory for a given type.
func RegisterL2CacheFactory(ct L2CacheType, f L2CacheFactory) {
l2locker.Lock()
defer l2locker.Unlock()
cacheRegistry[ct] = f
}
// GetL2Cache gets the cache (client) for the specified type.
// It returns nil if no factory is registered for that type.
func GetL2Cache(options TransactionOptions) L2Cache {
l2locker.Lock()
defer l2locker.Unlock()
key := getCacheKey(options)
if instance, ok := cacheInstances[key]; ok {
return instance
}
if f, ok := cacheRegistry[options.CacheType]; ok {
instance := f(options)
cacheInstances[key] = instance
return instance
}
return nil
}
func getCacheKey(options TransactionOptions) string {
if options.CacheType == Redis && options.RedisConfig != nil {
var address, password string
var db int
if options.RedisConfig.URL != "" {
u, err := url.Parse(options.RedisConfig.URL)
if err == nil {
address = u.Host
password, _ = u.User.Password()
path := strings.TrimPrefix(u.Path, "/")
if path != "" {
db, _ = strconv.Atoi(path)
}
return fmt.Sprintf("redis://%s@%s/%d", password, address, db)
}
// If parse fails, fall back to raw URL
return options.RedisConfig.URL
}
return fmt.Sprintf("redis://%s@%s/%d", options.RedisConfig.Password, options.RedisConfig.Address, options.RedisConfig.DB)
}
return fmt.Sprintf("%d", options.CacheType)
}