当前位置: 首页>>代码示例>>Golang>>正文


Golang KeysAPI.Set方法代码示例

本文整理汇总了Golang中github.com/coreos/etcd/client.KeysAPI.Set方法的典型用法代码示例。如果您正苦于以下问题:Golang KeysAPI.Set方法的具体用法?Golang KeysAPI.Set怎么用?Golang KeysAPI.Set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/coreos/etcd/client.KeysAPI的用法示例。


在下文中一共展示了KeysAPI.Set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Create

// Create etcd directory structure from a map, slice or struct.
func Create(kapi client.KeysAPI, path string, val reflect.Value) error {
	switch val.Kind() {
	case reflect.Ptr:
		orig := val.Elem()
		if !orig.IsValid() {
			return nil
		}
		if err := Create(kapi, path, orig); err != nil {
			return err
		}
	case reflect.Interface:
		orig := val.Elem()
		if err := Create(kapi, path, orig); err != nil {
			return err
		}
	case reflect.Struct:
		for i := 0; i < val.NumField(); i++ {
			t := val.Type().Field(i)
			k := t.Tag.Get("etcd")
			if err := Create(kapi, path+"/"+k, val.Field(i)); err != nil {
				return err
			}
		}
	case reflect.Map:
		if strings.HasPrefix(pathx.Base(path), "_") {
			log.Printf("create hidden directory in etcd: %s", path)
		}
		for _, k := range val.MapKeys() {
			v := val.MapIndex(k)
			if err := Create(kapi, path+"/"+k.String(), v); err != nil {
				return err
			}
		}
	case reflect.Slice:
		for i := 0; i < val.Len(); i++ {
			Create(kapi, fmt.Sprintf("%s/%d", path, i), val.Index(i))
		}
	case reflect.String:
		if strings.HasPrefix(pathx.Base(path), "_") {
			log.Printf("set hidden key in etcd: %s", path)
		}
		_, err := kapi.Set(context.TODO(), path, val.String(), nil)
		if err != nil {
			return err
		}
	case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
		if strings.HasPrefix(pathx.Base(path), "_") {
			log.Printf("set hidden key in etcd: %s", path)
		}
		_, err := kapi.Set(context.TODO(), path, fmt.Sprintf("%v", val.Interface()), nil)
		if err != nil {
			return err
		}
	default:
		return fmt.Errorf("unsupported type: %s for path: %s", val.Kind(), path)
	}

	return nil
}
开发者ID:mickep76,项目名称:etcdrest,代码行数:61,代码来源:etcdmap.go

示例2: mkCommandFunc

// mkCommandFunc executes the "mk" command.
func mkCommandFunc(c *cli.Context, ki client.KeysAPI) {
	if len(c.Args()) == 0 {
		handleError(ExitBadArgs, errors.New("key required"))
	}
	key := c.Args()[0]
	value, err := argOrStdin(c.Args(), os.Stdin, 1)
	if err != nil {
		handleError(ExitBadArgs, errors.New("value required"))
	}

	ttl := c.Int("ttl")

	ctx, cancel := contextWithTotalTimeout(c)
	// Since PrevNoExist means that the Node must not exist previously,
	// this Set method always creates a new key. Therefore, mk command
	// succeeds only if the key did not previously exist, and the command
	// prevents one from overwriting values accidentally.
	resp, err := ki.Set(ctx, key, value, &client.SetOptions{TTL: time.Duration(ttl) * time.Second, PrevExist: client.PrevNoExist})
	cancel()
	if err != nil {
		handleError(ExitServerError, err)
	}

	printResponseKey(resp, c.GlobalString("output"))
}
开发者ID:carriercomm,项目名称:etcd,代码行数:26,代码来源:mk_command.go

示例3: mustCreateServiceDirectory

func mustCreateServiceDirectory(ctx context.Context, kApi etcd.KeysAPI, basepath string) {
	myContext, myCancel := context.WithTimeout(ctx, DefaultTimeout)
	defer myCancel()

	_, err := kApi.Set(myContext, basepath, "", &etcd.SetOptions{Dir: true, PrevExist: etcd.PrevNoExist})
	log.WithField("error", err).Warn("error creating servicedef directory")
}
开发者ID:christian-blades-cb,项目名称:desoto,代码行数:7,代码来源:main.go

示例4: doServerBeat

func doServerBeat(kapi client.KeysAPI) {
	var key = runningbase + *serverbeatname

	myuuid := uuid.NewV4()
	uuidstring := myuuid.String()

	fmt.Println("Badum")
	_, err := kapi.Set(context.TODO(), key, uuidstring, &client.SetOptions{PrevExist: client.PrevNoExist, TTL: time.Second * 60})
	if err != nil {
		log.Fatal(err)
	}

	running := true
	counter := *serverbeatcount

	for running {
		time.Sleep(time.Second * time.Duration(*serverbeattime))
		fmt.Println("Badum")
		_, err := kapi.Set(context.TODO(), key, uuidstring, &client.SetOptions{PrevExist: client.PrevExist, TTL: time.Second * 60, PrevValue: uuidstring})
		if err != nil {
			log.Fatal(err)
		}
		if *serverbeatcount != 0 {
			counter = counter - 1
			if counter == 0 {
				running = false
			}
		}
	}

	_, err = kapi.Delete(context.TODO(), key, &client.DeleteOptions{PrevValue: uuidstring})
	if err != nil {
		log.Fatal(err)
	}
}
开发者ID:compose-ex,项目名称:examplco2,代码行数:35,代码来源:examplco2.go

示例5: mkCommandFunc

// mkCommandFunc executes the "mk" command.
func mkCommandFunc(c *cli.Context, ki client.KeysAPI) {
	if len(c.Args()) == 0 {
		handleError(ExitBadArgs, errors.New("key required"))
	}
	key := c.Args()[0]
	value, err := argOrStdin(c.Args(), os.Stdin, 1)
	if err != nil {
		handleError(ExitBadArgs, errors.New("value required"))
	}

	ttl := c.Int("ttl")
	inorder := c.Bool("in-order")

	var resp *client.Response
	ctx, cancel := contextWithTotalTimeout(c)
	if !inorder {
		// Since PrevNoExist means that the Node must not exist previously,
		// this Set method always creates a new key. Therefore, mk command
		// succeeds only if the key did not previously exist, and the command
		// prevents one from overwriting values accidentally.
		resp, err = ki.Set(ctx, key, value, &client.SetOptions{TTL: time.Duration(ttl) * time.Second, PrevExist: client.PrevNoExist})
	} else {
		// If in-order flag is specified then create an inorder key under
		// the directory identified by the key argument.
		resp, err = ki.CreateInOrder(ctx, key, value, &client.CreateInOrderOptions{TTL: time.Duration(ttl) * time.Second})
	}
	cancel()
	if err != nil {
		handleError(ExitServerError, err)
	}

	printResponseKey(resp, c.GlobalString("output"))
}
开发者ID:luxas,项目名称:flannel,代码行数:34,代码来源:mk_command.go

示例6: Store

func Store(api etcd.KeysAPI, path string, ttl time.Duration) frameworkid.Storage {
	// TODO(jdef) validate Config
	return &storage{
		LookupFunc: func(ctx context.Context) (string, error) {
			if response, err := api.Get(ctx, path, nil); err != nil {
				if !etcdutil.IsEtcdNotFound(err) {
					return "", fmt.Errorf("unexpected failure attempting to load framework ID from etcd: %v", err)
				}
			} else {
				return response.Node.Value, nil
			}
			return "", nil
		},
		RemoveFunc: func(ctx context.Context) (err error) {
			if _, err = api.Delete(ctx, path, &etcd.DeleteOptions{Recursive: true}); err != nil {
				if !etcdutil.IsEtcdNotFound(err) {
					return fmt.Errorf("failed to delete framework ID from etcd: %v", err)
				}
			}
			return
		},
		StoreFunc: func(ctx context.Context, id string) (err error) {
			_, err = api.Set(ctx, path, id, &etcd.SetOptions{TTL: ttl})
			return
		},
	}
}
开发者ID:CodeJuan,项目名称:kubernetes,代码行数:27,代码来源:etcd.go

示例7: setJob

func setJob(ctx context.Context, kapi client.KeysAPI, j *job) error {
	errChan := make(chan error)
	done := make(chan struct{})
	go func() {
		buf := new(bytes.Buffer)
		if err := json.NewEncoder(buf).Encode(j); err != nil {
			errChan <- err
			return
		}
		value := buf.String()
		fmt.Println("setJob:", value)
		opts := &client.SetOptions{}
		if _, err := kapi.Set(ctx, j.ETCDKey, value, opts); err != nil {
			errChan <- err
			return
		}
		done <- struct{}{}
	}()
	select {
	case <-done:
		return nil

	case v := <-errChan:
		return v

	case <-ctx.Done():
		return ctx.Err()
	}
}
开发者ID:agupt,项目名称:learn,代码行数:29,代码来源:client.go

示例8: sync

func sync(kapi client.KeysAPI, syncChannel chan blocker.ControlMsg) {
	for {
		msg := <-syncChannel
		start := time.Now()
		var folder string
		if msg.Ip.To4() == nil {
			folder = "dblock6/"
		} else {
			folder = "dblock/"
		}
		_, err := kapi.Set(context.Background(), folder+msg.Ip.String(), "0", &client.SetOptions{TTL: 60 * time.Second, PrevExist: client.PrevNoExist})
		if err != nil {
			if err.(client.Error).Code == client.ErrorCodeNodeExist {
				log.Print("Block already existed, not adding again")
			} else {
				log.Fatal(err)
			}
		} else {
			// print common key info
			log.Println("[sync]\tAdded block: " + msg.Ip.String())
		}
		elapsed := time.Since(start)
		log.Printf("sync took %s", elapsed)
		sync_timing.Observe(elapsed.Seconds())
	}
}
开发者ID:timbuchwaldt,项目名称:dblock,代码行数:26,代码来源:sync.go

示例9: NewPubSubTopicByKey

func NewPubSubTopicByKey(ctx context.Context, keyid string, ttl time.Duration, kapi etcdc.KeysAPI) (*EtcdPubSubTopic, error) {
	_, err := kapi.Get(ctx, keyid, nil)
	if IsKeyNotFound(err) {
		opt := &etcdc.SetOptions{PrevExist: etcdc.PrevNoExist, TTL: ttl, Dir: true}
		_, err = kapi.Set(ctx, keyid, "", opt)
		if err != nil && !IsCompareAndSwapFailure(err) && !IsNodeExists(err) {
			return nil, err
		}
	} else if err != nil {
		return nil, err
	}

	keepalive, err := NewNodeKeepAlive(keyid, ttl, kapi)
	if err != nil {
		return nil, err
	}

	dlog("signal: new signal(pub/sub) for %v, ttl:%v", keyid, ttl)

	return &EtcdPubSubTopic{
		ctx:       ctx,
		keyid:     keyid,
		kapi:      kapi,
		ttl:       ttl,
		keepalive: keepalive,
		stop:      make(chan bool),
	}, nil
}
开发者ID:lytics,项目名称:sereno,代码行数:28,代码来源:signal.go

示例10: setValues

func setValues(kapi client.KeysAPI, kvs map[string]string) error {
	for k, v := range kvs {
		if _, err := kapi.Set(context.Background(), k, v, &client.SetOptions{}); err != nil {
			return err
		}
	}
	return nil
}
开发者ID:lucmichalski,项目名称:vulcan-config-builder,代码行数:8,代码来源:all_test.go

示例11: importFunc

func importFunc(dir string, file string, f iodatafmt.DataFmt, replace bool, yes bool, e Etcdtool, c *cli.Context, ki client.KeysAPI) {
	// Check if dir exists and is a directory.
	exists, err := dirExists(dir, c, ki)
	if err != nil {
		fatalf("Specified dir doesn't exist: %s", dir)
	}

	if exists {
		exist, err := isDir(dir, c, ki)
		if err != nil {
			fatal(err.Error())
		}

		if exist {
			fatalf("Specified dir is not a directory: %s", dir)
		}
	}

	// Load file.
	m, err := iodatafmt.Load(file, f)
	if err != nil {
		fatal(err.Error())
	}

	// Validate data.
	if c.Bool("validate") {
		validateFunc(e, dir, m)
	}

	if exists {
		if replace {
			if !askYesNo(fmt.Sprintf("Do you want to overwrite data in directory: %s", dir)) {
				os.Exit(1)
			}

			// Delete dir.
			if _, err = ki.Delete(context.TODO(), dir, &client.DeleteOptions{Recursive: true}); err != nil {
				fatal(err.Error())
			}
		} else {
			if !yes {
				if !askYesNo(fmt.Sprintf("Do you want to overwrite data in directory: %s", dir)) {
					os.Exit(1)
				}
			}
		}
	} else {
		// Create dir.
		if _, err := ki.Set(context.TODO(), dir, "", &client.SetOptions{Dir: true}); err != nil {
			fatal(err.Error())
		}
	}

	// Import data.
	if err = etcdmap.Create(ki, dir, reflect.ValueOf(m)); err != nil {
		fatal(err.Error())
	}
}
开发者ID:mickep76,项目名称:etcdtool,代码行数:58,代码来源:import_command.go

示例12: setHostPort

func setHostPort(k client.KeysAPI, base, host, port string, ttl time.Duration) error {
	o := client.SetOptions{TTL: ttl}
	if _, err := k.Set(dctx(), base+"/host", host, &o); err != nil {
		return err
	}
	if _, err := k.Set(dctx(), base+"/port", port, &o); err != nil {
		return err
	}
	return nil
}
开发者ID:helgi,项目名称:pkg,代码行数:10,代码来源:etcd.go

示例13: doConfig

func doConfig(kapi client.KeysAPI) {
	var key = configbase + *configserver + "/" + *configvar

	resp, err := kapi.Set(context.TODO(), key, *configval, nil)

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(resp.Action + " " + resp.Node.Key + " to " + resp.Node.Value)
}
开发者ID:compose-ex,项目名称:examplco2,代码行数:11,代码来源:examplco2.go

示例14: put

func (s *Server) put(ctx context.Context, client etcd.KeysAPI, vulcanpath, servicename, instancename string) error {
	myContext, cancel := context.WithTimeout(ctx, DefaultTimeout)
	defer cancel()

	key := fmt.Sprintf(serverPathPattern, vulcanpath, servicename, instancename)
	se, err := json.Marshal(s)
	if err != nil {
		return err
	}

	_, err = client.Set(myContext, key, fmt.Sprintf("%s", se), &etcd.SetOptions{TTL: serverTTL, PrevExist: etcd.PrevIgnore})
	return err
}
开发者ID:christian-blades-cb,项目名称:desoto,代码行数:13,代码来源:vulcand.go

示例15: createDir

// createDir will create path if it doesn't exist and is not root.
func createDir(kapi client.KeysAPI, path string) error {
	if path != "/" {
		if _, err := kapi.Set(context.TODO(), path, "", &client.SetOptions{Dir: true, PrevExist: client.PrevNoExist}); err != nil {
			if etcdErr, ok := err.(client.Error); ok {
				if etcdErr.Code == client.ErrorCodeNodeExist {
					return nil
				}
			}
			return err
		}
	}
	return nil
}
开发者ID:mickep76,项目名称:etcdmap,代码行数:14,代码来源:etcdmap.go


注:本文中的github.com/coreos/etcd/client.KeysAPI.Set方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。