You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/pkg/naming/etcd/etcd_test.go

100 lines
1.8 KiB

6 years ago
package etcd
import (
"context"
"fmt"
"github.com/bilibili/kratos/pkg/naming"
"go.etcd.io/etcd/clientv3"
"google.golang.org/grpc"
"testing"
"time"
6 years ago
)
func TestNew(t *testing.T) {
config := &clientv3.Config{
Endpoints: []string{"127.0.0.1:2379"},
DialTimeout: time.Second * 3,
DialOptions: []grpc.DialOption{grpc.WithBlock()},
6 years ago
}
builder, err := New(config)
6 years ago
if err != nil {
6 years ago
fmt.Println("etcd 连接失败")
return
}
6 years ago
app1 := builder.Build("app1")
go func() {
fmt.Printf("Watch \n")
6 years ago
for {
select {
case <-app1.Watch():
6 years ago
fmt.Printf("app1 节点发生变化 \n")
6 years ago
}
6 years ago
}
}()
time.Sleep(time.Second)
6 years ago
app1Cancel, err := builder.Register(context.Background(), &naming.Instance{
AppID: "app1",
Hostname: "h1",
Zone: "z1",
6 years ago
})
6 years ago
app2Cancel, err := builder.Register(context.Background(), &naming.Instance{
AppID: "app2",
Hostname: "h5",
Zone: "z3",
6 years ago
})
6 years ago
if err != nil {
6 years ago
fmt.Println(err)
}
app2 := builder.Build("app2")
6 years ago
go func() {
6 years ago
fmt.Println("节点列表")
for {
fmt.Printf("app1: ")
6 years ago
r1, _ := app1.Fetch(context.Background())
if r1 != nil {
for z, ins := range r1.Instances {
fmt.Printf("zone: %s :", z)
for _, in := range ins {
fmt.Printf("app: %s host %s \n", in.AppID, in.Hostname)
6 years ago
}
}
} else {
fmt.Printf("\n")
6 years ago
}
fmt.Printf("app2: ")
6 years ago
r2, _ := app2.Fetch(context.Background())
if r2 != nil {
for z, ins := range r2.Instances {
fmt.Printf("zone: %s :", z)
for _, in := range ins {
fmt.Printf("app: %s host %s \n", in.AppID, in.Hostname)
6 years ago
}
}
} else {
fmt.Printf("\n")
6 years ago
}
time.Sleep(time.Second)
}
}()
6 years ago
time.Sleep(time.Second * 5)
6 years ago
fmt.Println("取消app1")
app1Cancel()
6 years ago
time.Sleep(time.Second * 10)
6 years ago
fmt.Println("取消app2")
app2Cancel()
time.Sleep(30 * time.Second)
6 years ago
}