-
Notifications
You must be signed in to change notification settings - Fork 21
/
client.go
82 lines (71 loc) · 1.72 KB
/
client.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
package katsubushi
import (
"context"
"strconv"
"time"
"github.com/Songmu/retry"
"github.com/pkg/errors"
)
// DefaultClientTimeout is default timeout for katsubushi client
var DefaultClientTimeout = 5 * time.Second
// Client is katsubushi client
type Client struct {
memcacheClients []*memcacheClient
}
// NewClient creates Client
func NewClient(addrs ...string) *Client {
c := &Client{
memcacheClients: make([]*memcacheClient, 0, len(addrs)),
}
for _, addr := range addrs {
c.memcacheClients = append(c.memcacheClients, newMemcacheClient(addr))
}
c.SetTimeout(DefaultClientTimeout)
return c
}
// SetTimeout sets timeout to katsubushi servers
func (c *Client) SetTimeout(t time.Duration) {
for _, mc := range c.memcacheClients {
mc.SetTimeout(t)
}
}
// Fetch fetches id from katsubushi
func (c *Client) Fetch(ctx context.Context) (uint64, error) {
errs := errors.New("no servers available")
for _, mc := range c.memcacheClients {
var id uint64
err := retry.Retry(2, 0, func() error {
var _err error
id, _err = mc.Get(ctx, "id")
return _err
})
if err != nil {
errs = errors.Wrap(errs, err.Error())
continue
}
return id, nil
}
return 0, errs
}
// FetchMulti fetches multiple ids from katsubushi
func (c *Client) FetchMulti(ctx context.Context, n int) ([]uint64, error) {
keys := make([]string, 0, n)
for i := 0; i < n; i++ {
keys = append(keys, strconv.Itoa(i))
}
errs := errors.New("no servers available")
for _, mc := range c.memcacheClients {
var ids []uint64
err := retry.Retry(2, 0, func() error {
var _err error
ids, _err = mc.GetMulti(ctx, keys)
return _err
})
if err != nil {
errs = errors.Wrap(errs, err.Error())
continue
}
return ids, nil
}
return nil, errs
}