• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang redis.Bool函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/garyburd/redigo/redis.Bool函数的典型用法代码示例。如果您正苦于以下问题:Golang Bool函数的具体用法?Golang Bool怎么用?Golang Bool使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: putPageWithoutLock

func putPageWithoutLock(w http.ResponseWriter, r *http.Request, u string, pageToLock string) {
	alreadyLocking, err := redis.Bool(rdo("EXISTS", "LOCK:"+u))
	if err != nil {
		log.Println("Unable to verify if user already has a page locked")
		fmt.Fprint(w, `{"editable":false, "reason":"Unable to verify if the page is locked"}`)
	} else if alreadyLocking {
		lockedPage, err := redis.String(rdo("GET", "LOCK:"+u))
		if err != nil {
			log.Println("Unable to get locked page for user:", u, err)
			fmt.Fprint(w, `{"editable":false, "reason":"Unable to locate the page currently locked by the user"}`)
		} else {
			if lockedPage == pageToLock {
				fmt.Fprint(w, `{"editable":true}`)
			} else {
				fmt.Fprint(w, `{"editable":false, "reason":"Your lock is being used on: `+lockedPage+`"}`)
			}
		}
	} else {
		lockObtained, err := redis.Bool(rdo("SETNX", "PAGE:"+pageToLock, u))
		if err != nil {
			log.Println("Failed to get lock on page where lock does not exist:", pageToLock, err)
			fmt.Fprint(w, `{"editable":false, "reason":"Failed to obtain lock on page"}`)
		} else {
			if lockObtained {
				rdo("SET", "LOCK:"+u, pageToLock)
				rdo("EXPIRE", "PAGE:"+pageToLock, pageLockTTL)
				rdo("EXPIRE", "LOCK:"+u, pageLockTTL)
				fmt.Fprint(w, `{"editable":true}`)
			} else {
				fmt.Fprint(w, `{"editable":false, "reason":"Unable to obtain lock on page"}`)
			}
		}
	}
}
开发者ID:richard-lyman,项目名称:edit,代码行数:34,代码来源:edit.go


示例2: TestRemoveRedisRecords

func TestRemoveRedisRecords(t *testing.T) {
	conn, clean := getConn()
	defer clean()

	// clean
	defer func() {
		conn.Do("FLUSHALL")
		conn.Close()
	}()

	_, err := conn.Do("SET", "abc", "123")
	check(err)
	_, err = conn.Do("SET", "a:b:c", "123")
	check(err)

	// remove file
	err = os.Remove(filepath("abc"))
	check(err)
	_, err = os.Stat(filepath("abc"))
	assert.True(t, os.IsNotExist(err))
	exist, err := redis.Bool(conn.Do("EXISTS", "abc"))
	assert.False(t, exist)

	// remove dir
	err = os.RemoveAll(filepath("a"))
	check(err)
	_, err = os.Stat(filepath("a"))
	check(err)
	exist, err = redis.Bool(conn.Do("EXISTS", "a:b:c"))
	assert.False(t, exist)
}
开发者ID:JoeyBurzynski,项目名称:redis-mount,代码行数:31,代码来源:all_test.go


示例3: putPage

func putPage(w http.ResponseWriter, r *http.Request, u string) {
	userExists, err := redis.Bool(rdo("EXISTS", "USER:"+u))
	if err != nil {
		log.Println("Attempt to edit with a non-existent account:", u, err)
		fmt.Fprint(w, `{"editable":false}`)
	} else {
		if userExists {
			setCookie(w, r, map[string]string{"u": u})
			pageToLock := r.URL.Path
			lockExists, err := redis.Bool(rdo("EXISTS", "PAGE:"+pageToLock))
			if err != nil {
				log.Println("Unable to test existence of lock for page:", pageToLock, err)
				fmt.Fprint(w, `{"editable":true}`)
			} else if lockExists {
				lockingUser, err := redis.String(rdo("GET", "PAGE:"+pageToLock))
				if err != nil {
					log.Println("Unable to get user for locked page:", pageToLock, err)
					fmt.Fprint(w, `{"editable":false, "reason":"Page is already locked by another user"}`)
				} else {
					if lockingUser == u {
						fmt.Fprint(w, `{"editable":true}`)
					} else {
						fmt.Fprint(w, `{"editable":false, "reason":"Page is currently being edited by someone else"}`)
					}
				}
			} else {
				putPageWithoutLock(w, r, u, pageToLock)
			}
		} else {
			log.Println("Attempt to edit with a user that doesn't exist:", u)
			fmt.Fprint(w, `{"editable":false}`)
		}
	}
}
开发者ID:richard-lyman,项目名称:edit,代码行数:34,代码来源:edit.go


示例4: QueueDocsetJob

// QueueDocsetJob will queue a job to build a docset for an artifact, if there
// is not yet one built.
func QueueDocsetJob(groupId, artifactId string, version string) error {
	var redisConn redis.Conn = redisconn.Get()

	id := groupId + ":" + artifactId

	exists, err := redis.Bool(redisConn.Do("SISMEMBER", "docsets", id))
	if err != nil {
		return err
	}
	if exists == true && version != "" {
		verExists, err := redis.Bool(redisConn.Do("SISMEMBER", "docset:"+id, version))
		if err != nil || verExists {
			return err
		}
	} else if exists == true {
		return nil
	}

	if err := QueueJob(map[string]string{
		"Job":        "build-docset",
		"ArtifactId": artifactId,
		"GroupId":    groupId,
		"Version":    version,
	}); err != nil {
		return err
	}

	return nil
}
开发者ID:samcday,项目名称:hosted-javadocsets,代码行数:31,代码来源:jobs.go


示例5: Test_MigrateAllKeysWithAPrefix

func Test_MigrateAllKeysWithAPrefix(t *testing.T) {
	ClearRedis()

	config = Config{
		Source:  sourceServer.url,
		Dest:    destServer.url,
		Workers: 1,
		Batch:   10,
		Prefix:  "bar",
	}

	for i := 0; i < 100; i++ {
		key := fmt.Sprintf("bar:%d", i)
		sourceServer.conn.Do("SET", key, i)
	}

	sourceServer.conn.Do("SET", "baz:foo", "yolo")

	RunAction(migrateKeys)

	for i := 0; i < 100; i++ {
		key := fmt.Sprintf("bar:%d", i)
		exists, _ := redis.Bool(destServer.conn.Do("EXISTS", key))

		if !exists {
			t.Errorf("Could not find a key %d that should have been migrated", key)
		}
	}

	exists, _ := redis.Bool(destServer.conn.Do("EXISTS", "baz:foo"))

	if exists {
		t.Errorf("Found a key %s that should not have been migrated", "baz:foo")
	}
}
开发者ID:tomzhang,项目名称:migr8,代码行数:35,代码来源:migrate_test.go


示例6: article_vote

func article_vote(user, article string, vt VTYPE) {
	now := time.Now()
	cutoff := now.Unix() - ONE_WEEK_IN_SECONDS
	t, _ := redis.Int64(c.Do("ZSCORE", "time:", article))
	if t < cutoff {
		return
	}
	id := getID(article)
	switch vt {
	case UPVOTE:
		//
		bm, _ := redis.Int(c.Do("SMOVE", "voted_down", "voted_up", user))
		if bm != 1 {
			//first vote
			b, _ := redis.Bool(c.Do("SADD", fmt.Sprintf("voted_up:%s", id), user))
			if b {
				c.Do("ZINCRBY", "score:", VOTE_SCORE, article)
				c.Do("HINCRBY", article, "votes", 1)
			} else {
				//already upvoted
				//cancel vote
				c.Do("ZINCRBY", "score:", -VOTE_SCORE, article)
				c.Do("HINCRBY", article, "votes", -1)
				c.Do("SREM", fmt.Sprintf("voted_up:%s", id), user)
			}
		} else {
			//switch from downvote to upvote
			c.Do("ZINCRBY", "score:", VOTE_SCORE, article)
			c.Do("HINCRBY", article, "votes", 1)
		}
	case DOWNVOTE:
		bm, _ := redis.Int(c.Do("SMOVE", "voted_up", "voted_down", user))
		if bm != 1 {
			//first vote
			b, _ := redis.Bool(c.Do("SADD", fmt.Sprintf("voted_down:%s", id), user))
			if b {
				c.Do("ZINCRBY", "score:", -VOTE_SCORE, article)
				c.Do("HINCRBY", article, "votes", -1)
			} else {
				//already downvoted
				//cancel vote
				c.Do("ZINCRBY", "score:", VOTE_SCORE, article)
				c.Do("HINCRBY", article, "votes", 1)
				//remove
				c.Do("SREM", fmt.Sprintf("voted_down:%s", id), user)
			}
		} else {
			//switch from upvote to downvote
			c.Do("ZINCRBY", "score:", -VOTE_SCORE, article)
			c.Do("HINCRBY", article, "votes", -1)
		}
	}

}
开发者ID:Catorpilor,项目名称:Redis-in-action,代码行数:54,代码来源:main.go


示例7: autoEnabled

func autoEnabled(conn redis.Conn, host, path string) (en bool, err error) {
	en, err = redis.Bool(conn.Do("GET", fmt.Sprintf(keyEnabled, host, path)))
	if err == redis.ErrNil {
		en, err = redis.Bool(conn.Do("SISMEMBER", keyAutoEnable, host))
		if err != nil {
			return
		}
		if en {
			conn.Do("SET", fmt.Sprintf(keyEnabled, host, path), "true")
		}
	}
	return
}
开发者ID:Luit,项目名称:comments,代码行数:13,代码来源:main.go


示例8: getSchedule

func getSchedule(username string) string {
	schedule := ""

	client := getClient()
	defer client.Close()

	days := []string{"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"}

	everyWeek := []string{}
	thisWeek := []string{}
	notThisWeek := []string{}
	for _, day := range days {
		readableDay := []rune(day)
		readableDay[0] = unicode.ToUpper(readableDay[0])

		if remote, _ := redis.Bool(client.Do("SISMEMBER", "remote.every."+day, username)); remote {
			everyWeek = append(everyWeek, string(readableDay))
		}

		if remote, _ := redis.Bool(client.Do("SISMEMBER", "remote.this."+day, username)); remote {
			thisWeek = append(thisWeek, string(readableDay))
		}

		if notRemote, _ := redis.Bool(client.Do("SISMEMBER", "not.remote.this."+day, username)); notRemote {
			notThisWeek = append(notThisWeek, string(readableDay))
		}
	}

	if len(everyWeek) > 0 {
		schedule += "You are remote every " + strings.Join(everyWeek, ", ") + ".\n"
	}

	if len(thisWeek) > 0 {
		if len(everyWeek) > 0 {
			schedule += "In addition to your normal schedule, you are also remote this "
		} else {
			schedule += "You are remote this "
		}
		schedule += strings.Join(thisWeek, ", ") + ".\n"
	}

	if len(notThisWeek) > 0 {
		schedule += "You are not remote this " + strings.Join(notThisWeek, ", ") + ".\n"
	}

	if len(everyWeek) == 0 && len(thisWeek) == 0 {
		schedule += "You have no remote days scheduled.\n"
	}

	return schedule
}
开发者ID:griffy,项目名称:slack-status-scheduler,代码行数:51,代码来源:scheduler.go


示例9: TestRedisSync_IntendedUsage

// Intended usage
func TestRedisSync_IntendedUsage(t *testing.T) {
	_, err := pool.Get().Do("FLUSHDB")
	if err != nil {
		t.Fatal("Error flushing database")
	}
	rs := &RedisSync{Key: "special flower", Pool: pool, ErrChan: make(chan error, 1), Timeout: 1 * time.Second}

	rs.Lock()
	err = <-rs.ErrChan
	if err != nil {
		t.Fatal("failed to obtain lock", err)
	}
	exists, err := redis.Bool(pool.Get().Do("EXISTS", "special flower.lock"))
	if err != nil {
		t.Fatal("eror checking if lock key exists")
	}
	if exists == false {
		t.Fatal("lock key doesn't exist after lock")
	}

	hasLock := rs.HasLock()
	err = <-rs.ErrChan
	if err != nil {
		t.Fatal("failed to check lock", rs.Key, err)
	}
	if !hasLock {
		t.Fatal("HasLock should return true")
	}

	rs.Unlock()
	err = <-rs.ErrChan
	if err != nil {
		t.Fatal("failed to unlock key", rs.Key, err)
	}
	exists, err = redis.Bool(pool.Get().Do("EXISTS", "special flower.lock"))
	if err != nil {
		t.Fatal("eror checking if lock key exists", err)
	}
	if exists == true {
		t.Fatal("lock key still exist after unlock")
	}

	hasLock = rs.HasLock()
	err = <-rs.ErrChan
	if err != nil {
		t.Fatal("failed to check lock", rs.Key, err)
	}
	if hasLock {
		t.Fatal("HasLock should return false")
	}
}
开发者ID:the-control-group,项目名称:redissync,代码行数:52,代码来源:redissync_test.go


示例10: Stat

// Stat ensures that the digest is a member of the specified repository and
// forwards the descriptor request to the global blob store. If the media type
// differs for the repository, we override it.
func (rsrbds *repositoryScopedRedisBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	if err := dgst.Validate(); err != nil {
		return distribution.Descriptor{}, err
	}

	conn := rsrbds.upstream.pool.Get()
	defer conn.Close()

	// Check membership to repository first
	member, err := redis.Bool(conn.Do("SISMEMBER", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst))
	if err != nil {
		return distribution.Descriptor{}, err
	}

	if !member {
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	upstream, err := rsrbds.upstream.stat(ctx, conn, dgst)
	if err != nil {
		return distribution.Descriptor{}, err
	}

	// We allow a per repository mediatype, let's look it up here.
	mediatype, err := redis.String(conn.Do("HGET", rsrbds.blobDescriptorHashKey(dgst), "mediatype"))
	if err != nil {
		return distribution.Descriptor{}, err
	}

	if mediatype != "" {
		upstream.MediaType = mediatype
	}

	return upstream, nil
}
开发者ID:emerald-ci,项目名称:test-runner,代码行数:38,代码来源:redis.go


示例11: resume

func (p *JobQ) resume() error {
	c := p.pool.Get()
	defer c.Close()
	cntKey := p.Name + ":consumer:count"
	exists, err := redis.Bool(c.Do("EXISTS", cntKey))
	if err != nil {
		return err
	}
	if exists {
		cnt, err := redis.Int(c.Do("GET", cntKey))
		if err != nil {
			return err
		}
		for i := 0; i < cnt; i++ {
			n, err := p.consumers[i].Len()
			if err != nil {
				return err
			}
			for j := 0; j < n; j++ {
				if err := p.consumers[i].PopTo(p.inputQ, nil); err != nil {
					return err
				}
			}
		}
	}
	_, err = c.Do("SET", cntKey, len(p.consumers))
	return err
}
开发者ID:h12w,项目名称:redisq,代码行数:28,代码来源:job.go


示例12: CreateUser

func CreateUser(email, password string) (*User, error) {
	rd := pool.Get()
	defer rd.Close()

	exists, err := redis.Bool(rd.Do("EXISTS", Config.UserNamespace+email))

	if exists {
		return nil, fmt.Errorf("that account is already registered")
	} else if err != nil {
		return nil, err
	}

	// Create a token
	hash, err := abdi.Hash(password)
	if err != nil {
		return nil, err
	}
	user := User{
		Email:      email,
		HashedPass: hash,
	}

	data, err := json.Marshal(user)
	if err != nil {
		return nil, err
	}

	_, err = rd.Do("SET", Config.UserNamespace+email, data)
	if err != nil {
		return nil, err
	}
	return &user, nil
}
开发者ID:ds0nt,项目名称:klouds-master,代码行数:33,代码来源:auth.go


示例13: GetBool

func (c *CacheRedis) GetBool(key string) bool {
	val, err := redis.Bool(c.conn.Do("GET", key))
	if err != nil {
		return false
	}
	return val
}
开发者ID:kan,项目名称:million-timer,代码行数:7,代码来源:cache.go


示例14: RandomFortune

// Return a single random Fortune, from a random module
func RandomFortune(mod string) (*Fortune, error) {
	conn := Pool.Get()
	defer conn.Close()

	// ensure the specified module exists
	if mod != "" {
		member, err := redis.Bool(conn.Do("SISMEMBER", MODS_KEY, mod))
		if err != nil {
			return nil, err
		}
		if member == false {
			return nil, errors.New(fmt.Sprintf("module '%s' not found", mod))
		}
	}

	if mod == "" {
		mod2, err := redis.String(conn.Do("SRANDMEMBER", MODS_KEY))
		if err != nil {
			return nil, err
		}
		mod = mod2
	}

	fid, err := redis.Int(conn.Do("SRANDMEMBER", modKey(mod)))
	if err != nil {
		return nil, err
	}

	text, err := redis.String(conn.Do("GET", fortuneKey(fid)))
	if err != nil {
		return nil, err
	}

	return &Fortune{mod: mod, id: fid, text: text}, nil
}
开发者ID:noise,项目名称:fortune-redis-go,代码行数:36,代码来源:rfortune.go


示例15: saveComment

func saveComment(conn redis.Conn, req *commentSubmitRequest) (id int64, err error) {
	for {
		id = time.Now().Unix()
		var added bool
		added, err = redis.Bool(conn.Do("ZADD", fmt.Sprintf(keyAll, req.host, req.path), id, id))
		if err != nil {
			log.Println(err)
			return
		}
		if added {
			break
		}
		time.Sleep(time.Second)
	}
	var ok string
	ok, err = redis.String(conn.Do("HMSET", redis.Args{}.
		Add(fmt.Sprintf(keyComment, req.host, req.path, id)).
		AddFlat(req)...))
	if err != nil {
		return
	}
	if ok != "OK" {
		log.Println("Unexpected return value from HMSET: %q\n", ok)
	}
	return
}
开发者ID:Luit,项目名称:comments,代码行数:26,代码来源:main.go


示例16: Work

// Work runs an infinite loop, watching its database for new requests, starting job as requested,
// moving stream data back and forth, and updating job status as it changes.
func (w *Worker) Work() error {
	conn := w.pool.Get()
	defer conn.Close()
	for {
		Debugf("Waiting for job")
		// Get the list of current jobs
		// Wait for next start event
		vals, err := redis.Values(conn.Do("BLPOP", w.KeyPath("start"), "0"))
		if err != nil {
			return err
		}
		var id string
		if _, err := redis.Scan(vals[1:], &id); err != nil {
			return err
		}
		Debugf("Received instruction to start job %s", id)
		// Acquire lock on the job
		acquired, err := redis.Bool(conn.Do("SETNX", w.KeyPath(id), "me"))
		if err != nil {
			return err
		}
		Debugf("Acquiring lock for job %s... -> %s", id, acquired)
		// FIXME: set a dead man's switch with TTL & a periodic refresh
		if acquired {
			Debugf("Spawning goroutine for job %s", id)
			go func(id string) {
				if err := w.startJob(id); err != nil {
					fmt.Fprintf(os.Stderr, "Error starting job %s: %s\n", id, err)
				}
			}(id)
		}
	}
}
开发者ID:pombredanne,项目名称:beam,代码行数:35,代码来源:worker.go


示例17: LoadUserAccessToken

func LoadUserAccessToken(token string) (int64, int64, string, error) {
	conn := redis_pool.Get()
	defer conn.Close()

	key := fmt.Sprintf("access_token_%s", token)
	var uid int64
	var appid int64
	var uname string

	exists, err := redis.Bool(conn.Do("EXISTS", key))
	if err != nil {
		return 0, 0, "", err
	}
	if !exists {
		return 0, 0, "", errors.New("token non exists")
	}

	reply, err := redis.Values(conn.Do("HMGET", key, "user_id", "app_id", "user_name"))
	if err != nil {
		log.Info("hmget error:", err)
		return 0, 0, "", err
	}

	_, err = redis.Scan(reply, &uid, &appid, &uname)
	if err != nil {
		log.Warning("scan error:", err)
		return 0, 0, "", err
	}
	return appid, uid, uname, nil
}
开发者ID:keryoo,项目名称:voip_service,代码行数:30,代码来源:user.go


示例18: IsExist

// IsExist returns true if cached value exists.
func (r *RedisCache) IsExist(key string) bool {
	v, err := redigo.Bool(r.do("EXISTS", key))
	if err != nil {
		return false
	}
	return v
}
开发者ID:echo-contrib,项目名称:cache,代码行数:8,代码来源:redis.go


示例19: Contains

// Contains does a membership check on the repository blob set in redis. This
// is used as an access check before looking up global path information. If
// false is returned, the caller should still check the backend to if it
// exists elsewhere.
func (rlic *redisLayerInfoCache) Contains(ctx context.Context, repo string, dgst digest.Digest) (bool, error) {
	conn := rlic.pool.Get()
	defer conn.Close()

	ctxu.GetLogger(ctx).Debugf("(*redisLayerInfoCache).Contains(%q, %q)", repo, dgst)
	return redis.Bool(conn.Do("SISMEMBER", rlic.repositoryBlobSetKey(repo), dgst))
}
开发者ID:jhadvig,项目名称:origin,代码行数:11,代码来源:redis.go


示例20: Test_DoesNothingInDryRunModeForMigrate

func Test_DoesNothingInDryRunModeForMigrate(t *testing.T) {
	ClearRedis()

	config = Config{
		Source:  sourceServer.url,
		Workers: 1,
		Batch:   10,
		Prefix:  "bar",
		DryRun:  true,
		Dest:    destServer.url,
	}

	for i := 0; i < 100; i++ {
		key := fmt.Sprintf("bar:%d", i)
		sourceServer.conn.Do("SET", key, i)
	}

	RunAction(migrateKeys)

	for i := 0; i < 100; i++ {
		key := fmt.Sprintf("bar:%d", i)
		exists, _ := redis.Bool(destServer.conn.Do("EXISTS", key))

		if exists {
			t.Errorf("In DryRun mode, but found a key %d that was actually migrated", key)
		}
	}
}
开发者ID:tomzhang,项目名称:migr8,代码行数:28,代码来源:migrate_test.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang redis.Bytes函数代码示例发布时间:2022-05-23
下一篇:
Golang redistest.Dial函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap