-
Notifications
You must be signed in to change notification settings - Fork 48
/
example_test.go
53 lines (44 loc) · 1.18 KB
/
example_test.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
package consistent_test
import (
"log"
"testing"
"github.com/lafikl/consistent"
)
func Example_consistent(t *testing.T) {
c := consistent.New()
// adds the hosts to the ring
c.Add("127.0.0.1:8000")
c.Add("92.0.0.1:8000")
// Returns the host that owns `key`.
//
// As described in https://en.wikipedia.org/wiki/Consistent_hashing
//
// It returns ErrNoHosts if the ring has no hosts in it.
host, err := c.Get("/app.html")
if err != nil {
log.Fatal(err)
}
log.Println(host)
}
func Example_bounded() {
c := consistent.New()
// adds the hosts to the ring
c.Add("127.0.0.1:8000")
c.Add("92.0.0.1:8000")
// It uses Consistent Hashing With Bounded loads
// https://research.googleblog.com/2017/04/consistent-hashing-with-bounded-loads.html
// to pick the least loaded host that can serve the key
//
// It returns ErrNoHosts if the ring has no hosts in it.
//
host, err := c.GetLeast("/app.html")
if err != nil {
log.Fatal(err)
}
// increases the load of `host`, we have to call it before sending the request
c.Inc(host)
// send request or do whatever
log.Println("send request to", host)
// call it when the work is done, to update the load of `host`.
c.Done(host)
}