예제 #1
0
func main() {
	{
		c := consistent_hashing.New()
		c.Add("127.9.9.3:3322")
		c.Add("127.9.9.3:3323")
		c.Add("127.9.9.3:3324")
		c.Add("127.9.9.3:3325")
		c.Add("127.9.9.3:3326")
		c.Add("127.9.9.3:3327")
		c.Add("127.9.9.3:3328")
		c.Add("127.9.9.3:3329")
		servers := make(map[string]int32)
		for i := 0; i < 100000; i++ {
			n := rand.Intn(1000000000)
			key := fmt.Sprintf("%d", n)
			server, _ := c.Get(key)
			if v, ok := servers[server]; ok {
				servers[server] = v + 1
			} else {
				servers[server] += 0
			}
		}

		log.Printf("%v", servers)
	}

	{
		c := consistent_hashing.New()
		c.Add("127.9.9.3:3322")
		c.Add("127.9.9.3:3323")
		c.Add("127.9.9.3:3324")
		c.Add("127.9.9.3:3325")
		c.Add("127.9.9.3:3326")
		c.Add("127.9.9.3:3327")
		c.Add("127.9.9.3:3328")
		c.Add("127.9.9.3:3329")
		servers := make(map[string]int32)
		for i := 0; i < 100000; i++ {
			n := rand.Intn(1000000000)
			key := fmt.Sprintf("%d", n)
			server, _ := c.GetN(key, 2)
			for i := 0; i < 2; i++ {
				if v, ok := servers[server[i]]; ok {
					servers[server[i]] = v + 1
				} else {
					servers[server[i]] += 0
				}
			}
		}

		log.Printf("%v", servers)
	}
}
// serviceName is like "/services/busybox"
// endPoints is an array of "http://<etcd client ip:port>"
func (service *ConsistentService) Connect(serviceName string, endPoints []string) error {
	if service.connected {
		log.Printf("Can't connected twice")
		return errors.New("math: square root of negative number")
	}

	service.nodes = make(map[string]bool)

	service.consis = consistent_hashing.New()

	cfg := client.Config{
		Endpoints:               endPoints,
		Transport:               client.DefaultTransport,
		HeaderTimeoutPerRequest: time.Second,
	}

	var err error
	service.etcdClient, err = client.New(cfg)
	if err != nil {
		return err
	}
	kapi := client.NewKeysAPI(service.etcdClient)

	resp, err := kapi.Get(context.Background(), serviceName, nil)
	if err != nil {
		return err
	} else {
		if resp.Node.Dir {
			for _, peer := range resp.Node.Nodes {
				n := peer.Value
				if _, ok := service.nodes[n]; !ok {
					service.consis.Add(n)
					service.nodes[n] = true
				}
			}
		}
	}

	watcher := kapi.Watcher(serviceName, &client.WatcherOptions{Recursive: true})
	go service.watch(watcher)
	service.connected = true
	return nil
}