-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
63 lines (53 loc) · 1.35 KB
/
client.go
File metadata and controls
63 lines (53 loc) · 1.35 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
package picopgomemcache
import (
"context"
"sync"
// Please use github.com/picop-rd/gomemcache instead of github.com/bradfitz/gomemcache/memcache by replacing in go.mod
"github.com/bradfitz/gomemcache/memcache"
"github.com/picop-rd/picop-go/propagation"
picopprop "github.com/picop-rd/picop-go/propagation"
"github.com/picop-rd/picop-go/protocol/header"
)
type Client struct {
server []string
pool *sync.Map
PoolByEnvID bool
}
func New(server ...string) *Client {
return &Client{
server: server,
pool: &sync.Map{},
PoolByEnvID: true,
}
}
func (c *Client) DisablePoolByEnvID() {
c.PoolByEnvID = false
}
func (c *Client) Connect(ctx context.Context) *memcache.Client {
if !c.PoolByEnvID {
mc := memcache.New(c.server...)
mc.DialContext = DialContext(propagation.EnvID{})
return mc
}
h := header.NewV1()
propagation.EnvID{}.Inject(ctx, picopprop.NewPiCoPCarrier(h))
envID := h.Get(propagation.EnvIDHeader)
if client, ok := c.pool.Load(envID); ok {
return client.(*memcache.Client)
}
mc := memcache.New(c.server...)
mc.DialContext = DialContext(propagation.EnvID{})
c.pool.Store(envID, mc)
return mc
}
func (c *Client) Close() error {
if !c.PoolByEnvID {
return nil
}
var err error
c.pool.Range(func(key, value interface{}) bool {
err = value.(*memcache.Client).Close()
return err == nil
})
return err
}