-
Notifications
You must be signed in to change notification settings - Fork 0
/
clientcache.go
75 lines (60 loc) · 1.65 KB
/
clientcache.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
package mmpd
import (
"fmt"
"github.com/linkdata/deadlock"
)
type NetAddr struct {
network string
address string
}
type ClientCacheEntry struct {
NetAddr NetAddr
Options []ClientOption
*ReconnectingClient
}
type ClientCache struct {
clients map[NetAddr]*ClientCacheEntry
clientLock deadlock.RWMutex
}
func NewClientCache() *ClientCache {
return &ClientCache{
clients: make(map[NetAddr]*ClientCacheEntry),
}
}
func (cc *ClientCache) GetOrCreate(network, addr string, options ...ClientOption) (*ClientCacheEntry, error) {
netAddr := NetAddr{network: network, address: addr}
cc.clientLock.RLock()
if entry, ok := cc.clients[netAddr]; ok {
cc.clientLock.RUnlock()
fmt.Printf("mpd: using cached client for target %s %s\n", netAddr.network, netAddr.address)
return entry, nil
}
cc.clientLock.RUnlock()
cc.clientLock.Lock()
defer cc.clientLock.Unlock()
if entry, ok := cc.clients[netAddr]; ok {
fmt.Printf("mpd: using newly cached client for target %s %s\n", netAddr.network, netAddr.address)
return entry, nil
}
fmt.Printf("mpd: creating new client for target %s %s\n", netAddr.network, netAddr.address)
client, err := NewReconnectingClient(network, addr, options...)
if err != nil {
return nil, err
}
cce := &ClientCacheEntry{
NetAddr: netAddr,
Options: options,
ReconnectingClient: client,
}
cc.clients[netAddr] = cce
fmt.Printf("mpd: returning new client for target %s %s\n", netAddr.network, netAddr.address)
return cce, nil
}
func (cc *ClientCache) Shutdown() {
cc.clientLock.Lock()
defer cc.clientLock.Unlock()
for _, cce := range cc.clients {
_ = cce.Client.Close()
}
clear(cc.clients)
}