|
0 |
package etcd
|
|
1 |
|
|
2 |
import (
|
|
3 |
"fmt"
|
|
4 |
"time"
|
|
5 |
"io"
|
|
6 |
|
|
7 |
"github.com/go-kit/kit/log"
|
|
8 |
"github.com/go-kit/kit/endpoint"
|
|
9 |
"golang.org/x/net/context"
|
|
10 |
)
|
|
11 |
|
|
12 |
// Package sd/etcd provides a wrapper around the coroes/etcd key value store (https://github.com/coreos/etcd)
|
|
13 |
// This example assumes the user has an instance of etcd installed and running locally on port 2379
|
|
14 |
func Example() {
|
|
15 |
|
|
16 |
var (
|
|
17 |
prefix = "/services/foosvc/" // known at compile time
|
|
18 |
instance = "1.2.3.4:8080" // taken from runtime or platform, somehow
|
|
19 |
key = prefix + instance
|
|
20 |
value = "http://" + instance // based on our transport
|
|
21 |
)
|
|
22 |
|
|
23 |
client, err := NewClient(context.Background(), []string{"http://:2379"}, ClientOptions{
|
|
24 |
DialTimeout: 2 * time.Second,
|
|
25 |
DialKeepAlive: 2 * time.Second,
|
|
26 |
HeaderTimeoutPerRequest: 2 * time.Second,
|
|
27 |
})
|
|
28 |
|
|
29 |
// Instantiate new instance of *Registrar passing in test data
|
|
30 |
registrar := NewRegistrar(client, Service{
|
|
31 |
Key: key,
|
|
32 |
Value: value,
|
|
33 |
}, log.NewNopLogger())
|
|
34 |
// Register new test data to etcd
|
|
35 |
registrar.Register()
|
|
36 |
|
|
37 |
//Retrieve entries from etcd
|
|
38 |
_, err = client.GetEntries(key)
|
|
39 |
if err != nil {
|
|
40 |
fmt.Println(err)
|
|
41 |
}
|
|
42 |
|
|
43 |
factory := func(string) (endpoint.Endpoint, io.Closer, error) {
|
|
44 |
return endpoint.Nop, nil, nil
|
|
45 |
}
|
|
46 |
subscriber, _ := NewSubscriber(client, prefix, factory, log.NewNopLogger())
|
|
47 |
|
|
48 |
endpoints, err := subscriber.Endpoints()
|
|
49 |
if err != nil {
|
|
50 |
fmt.Printf("err: %v", err)
|
|
51 |
}
|
|
52 |
fmt.Println(len(endpoints)) // hopefully 1
|
|
53 |
|
|
54 |
// Deregister first instance of test data
|
|
55 |
registrar.Deregister()
|
|
56 |
|
|
57 |
endpoints, err = subscriber.Endpoints()
|
|
58 |
if err != nil {
|
|
59 |
fmt.Printf("err: %v", err)
|
|
60 |
}
|
|
61 |
fmt.Println(len(endpoints)) // hopefully 0
|
|
62 |
|
|
63 |
// Verify test data no longer exists in etcd
|
|
64 |
_, err = client.GetEntries(key)
|
|
65 |
if err != nil {
|
|
66 |
fmt.Println(err)
|
|
67 |
}
|
|
68 |
}
|