github.com/searKing/golang/go@v1.2.117/container/hashring/example_test.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package hashring_test 6 7 import ( 8 "fmt" 9 "log" 10 11 "github.com/searKing/golang/go/container/hashring" 12 ) 13 14 func ExampleNew() { 15 c := hashring.New() 16 c.AddNodes(hashring.StringNode("NodeA")) 17 c.AddNodes(hashring.StringNode("NodeB")) 18 c.AddNodes(hashring.StringNode("NodeC")) 19 users := []string{"Alice", "Bob ", "Eve ", "Carol", "Dave "} 20 for _, u := range users { 21 server, has := c.Get(u) 22 if !has { 23 log.Fatal() 24 } 25 fmt.Printf("%s => %s\n", u, server) 26 } 27 // Output: 28 // Alice => NodeB 29 // Bob => NodeA 30 // Eve => NodeA 31 // Carol => NodeC 32 // Dave => NodeA 33 } 34 35 func ExampleAdd() { 36 c := hashring.New() 37 c.AddNodes(hashring.StringNode("NodeA")) 38 c.AddNodes(hashring.StringNode("NodeB")) 39 c.AddNodes(hashring.StringNode("NodeC")) 40 users := []string{"Alice", "Bob ", "Eve ", "Carol", "Dave "} 41 fmt.Println("initial state [A, B, C]") 42 for _, u := range users { 43 server, has := c.Get(u) 44 if !has { 45 log.Fatal() 46 } 47 fmt.Printf("%s => %s\n", u, server) 48 } 49 c.AddNodes(hashring.StringNode("NodeD")) 50 c.AddNodes(hashring.StringNode("NodeE")) 51 fmt.Println("\nwith NodeD, NodeE [A, B, C, D, E]") 52 for _, u := range users { 53 server, has := c.Get(u) 54 if !has { 55 log.Fatal() 56 } 57 fmt.Printf("%s => %s\n", u, server) 58 } 59 // Output: 60 // initial state [A, B, C] 61 // Alice => NodeB 62 // Bob => NodeA 63 // Eve => NodeA 64 // Carol => NodeC 65 // Dave => NodeA 66 // 67 // with NodeD, NodeE [A, B, C, D, E] 68 // Alice => NodeB 69 // Bob => NodeA 70 // Eve => NodeA 71 // Carol => NodeE 72 // Dave => NodeA 73 } 74 75 func ExampleRemove() { 76 c := hashring.New() 77 c.AddNodes(hashring.StringNode("NodeA")) 78 c.AddNodes(hashring.StringNode("NodeB")) 79 c.AddNodes(hashring.StringNode("NodeC")) 80 //users := []string{"Alice", "Bob", "Eve", "Carol", "Dave", "Isaac", "Justin", "Mallory", "Oscar", "Pat", "Victor", "Trent", "Walter"} 81 users := []string{"Alice", "Bob ", "Eve ", "Carol", "Dave "} 82 fmt.Println("initial state [A, B, C]") 83 for _, u := range users { 84 server, has := c.Get(u) 85 if !has { 86 log.Fatal() 87 } 88 fmt.Printf("%s => %s\n", u, server) 89 } 90 c.RemoveNodes(hashring.StringNode("NodeA")) 91 fmt.Println("\nNodeA removed [B, C]") 92 for _, u := range users { 93 server, has := c.Get(u) 94 if !has { 95 log.Fatal() 96 } 97 fmt.Printf("%s => %s\n", u, server) 98 } 99 // Output: 100 // initial state [A, B, C] 101 // Alice => NodeB 102 // Bob => NodeA 103 // Eve => NodeA 104 // Carol => NodeC 105 // Dave => NodeA 106 // 107 // NodeA removed [B, C] 108 // Alice => NodeB 109 // Bob => NodeC 110 // Eve => NodeB 111 // Carol => NodeC 112 // Dave => NodeB 113 }