コード例 #1
0
ファイル: cmd_hash_test.go プロジェクト: Goyoo/codis-docker
func TestHashSetNX(t *testing.T) {
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	// New Hash
	v, err := redis.Int(c.Do("HSETNX", "wim", "zus", "jet"))
	ok(t, err)
	equals(t, 1, v)

	v, err = redis.Int(c.Do("HSETNX", "wim", "zus", "jet"))
	ok(t, err)
	equals(t, 0, v)

	// Just a new key
	v, err = redis.Int(c.Do("HSETNX", "wim", "aap", "noot"))
	ok(t, err)
	equals(t, 1, v)

	// Wrong key type
	s.Set("foo", "bar")
	_, err = redis.Int(c.Do("HSETNX", "foo", "nosuch", "nosuch"))
	assert(t, err != nil, "no HSETNX error")
}
コード例 #2
0
ファイル: shrink.go プロジェクト: natebrennand/shrtnr
// creates the requested shortened URL
func CreateURL(conn redis.Conn, longURL string, shortURL string) (string, error) {
	// randomly assign URL if not given
	if shortURL == "" {
		for { // loop until unique string
			shortURL = randURL()
			v, err := redis.Int(conn.Do("EXISTS", shortURL))
			if err == nil && v == 0 {
				break
			}
		}
	} else { // confirm that URL is free
		v, err := redis.Int(conn.Do("EXISTS", shortURL))
		if err != nil {
			return "", err
		} else if v == 1 {
			return "", UrlInUse
		}
	}
	// create hash record
	v, err := redis.String(conn.Do("HMSET", shortURL, LONG, longURL, COUNT, 0))
	if v != "OK" || err != nil {
		return "", err
	}

	return shortURL, err
}
コード例 #3
0
ファイル: cmd_hash_test.go プロジェクト: Goyoo/codis-docker
func TestHashExists(t *testing.T) {
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	s.HSet("wim", "zus", "jet")
	s.HSet("wim", "teun", "vuur")
	v, err := redis.Int(c.Do("HEXISTS", "wim", "zus"))
	ok(t, err)
	equals(t, 1, v)

	v, err = redis.Int(c.Do("HEXISTS", "wim", "nosuch"))
	ok(t, err)
	equals(t, 0, v)

	v, err = redis.Int(c.Do("HEXISTS", "nosuch", "nosuch"))
	ok(t, err)
	equals(t, 0, v)

	// Wrong key type
	s.Set("foo", "bar")
	_, err = redis.Int(c.Do("HEXISTS", "foo", "nosuch"))
	assert(t, err != nil, "no HDEL error")
}
コード例 #4
0
ファイル: router_test.go プロジェクト: zhenruyan/tsuru
func (s *S) TestUnsetTwoCNames(c *check.C) {
	router := hipacheRouter{prefix: "hipache"}
	err := router.AddBackend("myapp")
	c.Assert(err, check.IsNil)
	err = router.SetCName("myapp.com", "myapp")
	c.Assert(err, check.IsNil)
	cnames, err := redis.Int(conn.Do("LLEN", "cname:myapp"))
	c.Assert(err, check.IsNil)
	c.Assert(1, check.Equals, cnames)
	err = router.SetCName("myapptwo.com", "myapp")
	c.Assert(err, check.IsNil)
	cnames, err = redis.Int(conn.Do("LLEN", "cname:myapp"))
	c.Assert(err, check.IsNil)
	c.Assert(2, check.Equals, cnames)
	err = router.UnsetCName("myapp.com", "myapp")
	c.Assert(err, check.IsNil)
	cnames, err = redis.Int(conn.Do("LLEN", "cname:myapp"))
	c.Assert(err, check.IsNil)
	c.Assert(1, check.Equals, cnames)
	err = router.UnsetCName("myapptwo.com", "myapp")
	c.Assert(err, check.IsNil)
	cnames, err = redis.Int(conn.Do("LLEN", "cname:myapp"))
	c.Assert(err, check.IsNil)
	c.Assert(0, check.Equals, cnames)
}
コード例 #5
0
ファイル: db.go プロジェクト: yungyikim/simple
func (db *DB) CreateUser(login, name string) (int, error) {
	// allocate a connection
	c := db.Get()
	defer c.Close()
	// check if username is taken
	if exists, err := redis.Int(c.Do("HEXISTS", "users:", login)); err != nil || exists == 1 {
		return -1, err
	}

	// increment global user count
	id, err := redis.Int(c.Do("INCR", "user:id"))
	if err != nil {
		return -1, err
	}

	// we want to do a transaction so we use MULTI cmd1 cmd2 ... EXEC
	c.Do("MULTI")
	// register the username to the uid
	c.Do("HSET", "users:", login, id)
	// set fields for user structure
	c.Do("HMSET", "user:"******"login", login,
		"id", id, "name", name, "followers", "0", "following", "0",
		"posts", "0", "signup", time.Now().Unix())
	if _, err := c.Do("EXEC"); err != nil {
		return -1, err
	}

	return id, nil
}
コード例 #6
0
ファイル: subscriber.go プロジェクト: qorio/omni
func (this *tallySubscriberImpl) Queue(queue string, inbound <-chan interface{}) {
	go func() {
		var queueLength int = 0
		var err error
		queueLength, _ = redis.Int(this.queue.Do("LLEN", queue))
		for {
			select {
			case message := <-inbound:
				if queueLength >= this.settings.MaxQueueLength {
					// do a read of the length in the hope that at some point the queue starts to drain
					queueLength, err = redis.Int(this.queue.Do("LLEN", queue))
					if err != nil {
						glog.Warningln("error-llen", queue, err, this.settings)
					}
					if queueLength >= this.settings.MaxQueueLength {
						glog.Warningln("queue-length-exceeds-limit", this.settings.MaxQueueLength, queueLength)
						// drop the message
						continue
					}
				}
				queueLength, err = redis.Int(this.queue.Do("LPUSH", queue, message))
				if err != nil {
					glog.Warningln("error-lpush", queue, err, this.settings)
				}
			case stop := <-this.stop:
				if stop {
					return
				}
			}
		}
	}()
}
コード例 #7
0
ファイル: client.go プロジェクト: schmatz/coco-verify
func addResultsToWinsAndLosses(resultString string, gameSessionPair lib.GameSessionPair, r redis.Conn) {
	var winningIndex, losingIndex int
	if resultString == "tie" {
		_, err := redis.Int(r.Do("SADD", gameSessionPair[0].GetTieRedisKey(), gameSessionPair[1].ID.Hex()))
		if err != nil {
			panic(err)
		}
		_, err = redis.Int(r.Do("SADD", gameSessionPair[1].GetTieRedisKey(), gameSessionPair[0].ID.Hex()))
		if err != nil {
			panic(err)
		}
	} else {
		switch resultString {
		case "humans":
			winningIndex = 0
			losingIndex = 1
		case "ogres":
			winningIndex = 1
			losingIndex = 0
		default:
			fmt.Println("You screwed up with the switch, buddy")
		}
		_, err := redis.Int(r.Do("SADD", gameSessionPair[winningIndex].GetWinningRedisKey(), gameSessionPair[losingIndex].ID.Hex()))
		if err != nil {
			panic(err)
		}

		_, err = redis.Int(r.Do("SADD", gameSessionPair[losingIndex].GetLosingRedisKey(), gameSessionPair[winningIndex].ID.Hex()))
		if err != nil {
			panic(err)
		}

	}

}
コード例 #8
0
ファイル: cmd_zset_test.go プロジェクト: nodephp/ledisdb
func TestZSetRank(t *testing.T) {
	startTestApp()

	c := getTestConn()
	defer c.Close()

	key := []byte("myzset")
	if _, err := redis.Int(c.Do("zadd", key, 1, "a", 2, "b", 3, "c", 4, "d")); err != nil {
		t.Fatal(err)
	}

	if n, err := redis.Int(c.Do("zrank", key, "c")); err != nil {
		t.Fatal(err)
	} else if n != 2 {
		t.Fatal(n)
	}

	if _, err := redis.Int(c.Do("zrank", key, "e")); err != redis.ErrNil {
		t.Fatal(err)
	}

	if n, err := redis.Int(c.Do("zrevrank", key, "c")); err != nil {
		t.Fatal(err)
	} else if n != 1 {
		t.Fatal(n)
	}

	if _, err := redis.Int(c.Do("zrevrank", key, "e")); err != redis.ErrNil {
		t.Fatal(err)
	}
}
コード例 #9
0
ファイル: redislist.go プロジェクト: cautonwong/chatserver
// 返回名称为key的list的长度
func (this *RedisListHelper) GetLength(key string) int {
	var (
		n   int
		err error
	)

	if atomic.CompareAndSwapInt32(&this.readMark1, 0, 1) {
		n, err = redis.Int(this.readCon1.Do("LLEN", key))
		atomic.StoreInt32(&this.readMark1, 0)

	} else if atomic.CompareAndSwapInt32(&this.readMark2, 0, 1) {
		n, err = redis.Int(this.readCon2.Do("LLEN", key))
		atomic.StoreInt32(&this.readMark2, 0)

	} else if atomic.CompareAndSwapInt32(&this.readMark3, 0, 1) {
		n, err = redis.Int(this.readCon3.Do("LLEN", key))
		atomic.StoreInt32(&this.readMark3, 0)

	} else if atomic.CompareAndSwapInt32(&this.readMark4, 0, 1) {
		n, err = redis.Int(this.readCon4.Do("LLEN", key))
		atomic.StoreInt32(&this.readMark4, 0)
	}

	if err != nil {
		return 0
	}
	return n
}
コード例 #10
0
ファイル: cmd_list_test.go プロジェクト: nodephp/ledisdb
func TestListMPush(t *testing.T) {
	startTestApp()
	c := getTestConn()
	defer c.Close()

	key := []byte("b")
	if n, err := redis.Int(c.Do("rpush", key, 1, 2, 3)); err != nil {
		t.Fatal(err)
	} else if n != 3 {
		t.Fatal(n)
	}

	if err := testListRange(key, 0, 3, 1, 2, 3); err != nil {
		t.Fatal(err)
	}

	if n, err := redis.Int(c.Do("lpush", key, 1, 2, 3)); err != nil {
		t.Fatal(err)
	} else if n != 6 {
		t.Fatal(n)
	}

	if err := testListRange(key, 0, 6, 3, 2, 1, 1, 2, 3); err != nil {
		t.Fatal(err)
	}
}
コード例 #11
0
ファイル: offlinemsg.go プロジェクト: neutony/chatserver
// 获取uuid的离线消息数量
func GetMsgNum(uuid string) int {

	var (
		n   int
		err error
	)

	if atomic.CompareAndSwapInt32(&offlinemsg_readMark1, 0, 1) {
		n, err = redis.Int(offlinemsg_readCon1.Do("LLEN", uuid))
		atomic.StoreInt32(&offlinemsg_readMark1, 0)

	} else if atomic.CompareAndSwapInt32(&offlinemsg_readMark2, 0, 1) {
		n, err = redis.Int(offlinemsg_readCon2.Do("LLEN", uuid))
		atomic.StoreInt32(&offlinemsg_readMark2, 0)

	} else if atomic.CompareAndSwapInt32(&offlinemsg_readMark3, 0, 1) {
		n, err = redis.Int(offlinemsg_readCon3.Do("LLEN", uuid))
		atomic.StoreInt32(&offlinemsg_readMark3, 0)

	} else if atomic.CompareAndSwapInt32(&offlinemsg_readMark4, 0, 1) {
		n, err = redis.Int(offlinemsg_readCon4.Do("LLEN", uuid))
		atomic.StoreInt32(&offlinemsg_readMark4, 0)
	}

	if err != nil {
		return 0
	}
	return n
}
コード例 #12
0
ファイル: gokiq_test.go プロジェクト: Nitrino/gokiq
func TestEnqueue(t *testing.T) {
	conn := pool.Get()
	defer conn.Close()

	job.Enqueue(pool)

	expected := fmt.Sprintf(`{"jid":"%s","retry":false,"queue":"default","class":"HardWorder","args":[],"enqueued_at":%d}`,
		job.JID,
		job.EnqueuedAt)
	actual := job.toJSON()

	if expected != actual {
		t.Errorf("Excepted JSON to be %s, got %s", expected, job.toJSON())
	}

	count, _ := redis.Int(conn.Do("SISMEMBER", "queues", job.Queue))

	if count != 1 {
		t.Error("Expected queues list to have the correct queue but didn't found it.")
	}

	count, _ = redis.Int(conn.Do("LLEN", "queue:default"))

	if count != 1 {
		t.Errorf("Expected the queue to have exactly one job but found %d", count)
	}

	resetRedis(pool)
}
コード例 #13
0
ファイル: redis_test.go プロジェクト: kalbasit/beego
func TestRedisCache(t *testing.T) {
	bm, err := cache.NewCache("redis", `{"conn": "127.0.0.1:6379"}`)
	if err != nil {
		t.Error("init err")
	}
	if err = bm.Put("astaxie", 1, 10); err != nil {
		t.Error("set Error", err)
	}
	if !bm.IsExist("astaxie") {
		t.Error("check err")
	}

	time.Sleep(10 * time.Second)

	if bm.IsExist("astaxie") {
		t.Error("check err")
	}
	if err = bm.Put("astaxie", 1, 10); err != nil {
		t.Error("set Error", err)
	}

	if v, _ := redis.Int(bm.Get("astaxie"), err); v != 1 {
		t.Error("get err")
	}

	if err = bm.Incr("astaxie"); err != nil {
		t.Error("Incr Error", err)
	}

	if v, _ := redis.Int(bm.Get("astaxie"), err); v != 2 {
		t.Error("get err")
	}

	if err = bm.Decr("astaxie"); err != nil {
		t.Error("Decr Error", err)
	}

	if v, _ := redis.Int(bm.Get("astaxie"), err); v != 1 {
		t.Error("get err")
	}
	bm.Delete("astaxie")
	if bm.IsExist("astaxie") {
		t.Error("delete err")
	}
	//test string
	if err = bm.Put("astaxie", "author", 10); err != nil {
		t.Error("set Error", err)
	}
	if !bm.IsExist("astaxie") {
		t.Error("check err")
	}

	if v, _ := redis.String(bm.Get("astaxie"), err); v != "author" {
		t.Error("get err")
	}
	// test clear all
	if err = bm.ClearAll(); err != nil {
		t.Error("clear all err")
	}
}
コード例 #14
0
ファイル: cmd_list_test.go プロジェクト: Goyoo/codis-docker
func TestLlen(t *testing.T) {
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	s.Push("l", "aap", "noot", "mies", "vuur")

	{
		el, err := redis.Int(c.Do("LLEN", "l"))
		ok(t, err)
		equals(t, 4, el)
	}

	// Non exising key
	{
		el, err := redis.Int(c.Do("LLEN", "nonexisting"))
		ok(t, err)
		equals(t, 0, el)
	}

	// Wrong type of key
	{
		_, err := redis.String(c.Do("SET", "str", "value"))
		ok(t, err)
		_, err = redis.Int(c.Do("LLEN", "str"))
		assert(t, err != nil, "LLEN error")
		// Too many arguments
		_, err = redis.String(c.Do("LLEN", "too", "many"))
		assert(t, err != nil, "LLEN error")
	}
}
コード例 #15
0
ファイル: fake_test.go プロジェクト: gmlexx/redigomock
func TestHLen(t *testing.T) {
	c := NewFakeRedis()
	c.Do("HSET", "foo", "k1", "v1")
	c.Do("HSET", "foo", "k2", "v2")
	assertInt(t, must(redis.Int(c.Do("HLEN", "foo"))), 2)
	assertInt(t, must(redis.Int(c.Do("HLEN", "empty"))), 0)
}
コード例 #16
0
func ScheduledSpec(c gospec.Context) {
	scheduled := newScheduled(RETRY_KEY)

	was := Config.namespace
	Config.namespace = "prod:"

	c.Specify("empties retry queues up to the current time", func() {
		conn := Config.Pool.Get()
		defer conn.Close()

		now := time.Now().Unix()

		message1, _ := NewMsg("{\"queue\":\"default\",\"foo\":\"bar1\"}")
		message2, _ := NewMsg("{\"queue\":\"myqueue\",\"foo\":\"bar2\"}")
		message3, _ := NewMsg("{\"queue\":\"default\",\"foo\":\"bar3\"}")

		conn.Do("zadd", "prod:"+RETRY_KEY, now-60, message1.ToJson())
		conn.Do("zadd", "prod:"+RETRY_KEY, now-10, message2.ToJson())
		conn.Do("zadd", "prod:"+RETRY_KEY, now+60, message3.ToJson())

		scheduled.poll(false)

		defaultCount, _ := redis.Int(conn.Do("llen", "prod:queue:default"))
		myqueueCount, _ := redis.Int(conn.Do("llen", "prod:queue:myqueue"))
		pending, _ := redis.Int(conn.Do("zcard", "prod:"+RETRY_KEY))

		c.Expect(defaultCount, Equals, 1)
		c.Expect(myqueueCount, Equals, 1)
		c.Expect(pending, Equals, 1)
	})

	Config.namespace = was
}
コード例 #17
0
ファイル: extra_incr.go プロジェクト: cougar731/codis
func (tc *ExtraIncrTestCase) groupfetch(c1, c2 redis.Conn, key string) int {
	r1, e1 := c1.Do("get", key)
	r2, e2 := c2.Do("get", key)
	if e1 != nil || e2 != nil {
		Panic("groupfetch key = %s, e1 = %s, e2 = %s", key, e1, e2)
	}
	if r1 == nil && r2 == nil {
		Panic("groupfetch key = %s, r1 == nil && r2 == nil", key)
	}
	if r1 != nil && r2 != nil {
		Panic("groupfetch key = %s, r1 != nil && r2 != nil, %v %v", key, r1, r2)
	}
	if r1 != nil {
		if v, err := redis.Int(r1, nil); err != nil {
			Panic("groupfetch key = %s, error = %s", key, err)
		} else {
			return v
		}
	}
	if r2 != nil {
		if v, err := redis.Int(r2, nil); err != nil {
			Panic("groupfetch key = %s, error = %s", key, err)
		} else {
			return v
		}
	}
	return -1
}
コード例 #18
0
ファイル: cmd_generic_test.go プロジェクト: jameswei/xcodis
func TestExpireat(t *testing.T) {
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	// Not volatile yet
	{
		equals(t, 0, s.Expire("foo"))
		b, err := redis.Int(c.Do("TTL", "foo"))
		ok(t, err)
		equals(t, -2, b)
	}

	// Set something
	{
		_, err := c.Do("SET", "foo", "bar")
		ok(t, err)
		// Key exists, but no Expire set yet.
		b, err := redis.Int(c.Do("TTL", "foo"))
		ok(t, err)
		equals(t, -1, b)

		n, err := redis.Int(c.Do("EXPIREAT", "foo", 1234567890))
		ok(t, err)
		equals(t, 1, n) // EXPIREAT returns 1 on success.

		equals(t, 1234567890, s.Expire("foo"))
		b, err = redis.Int(c.Do("TTL", "foo"))
		ok(t, err)
		equals(t, 1234567890, b)
		equals(t, 1234567890, s.Expire("foo"))
	}
}
コード例 #19
0
ファイル: main.go プロジェクト: elvingm/cc-gif-group-api
func init() { // connect to Redis on init, and get highest group ID
	err := goenv.Load()
	if err != nil {
		fmt.Println("Missing environment variables file")
		panic(err)
	}

	rC := RedisConnection()
	defer rC.Close()

	groupSeqValue, err := redis.Int(rC.Do("GET", "id:groups"))
	if err != nil {
		_, err := rC.Do("SET", "id:groups", 1) // initialize if doesn't exist
		ErrorHandler(err)

		groupSeqValue = 1
	}

	gifSeqValue, err := redis.Int(rC.Do("GET", "id:gifs"))
	if err != nil {
		_, err := rC.Do("SET", "id:gifs", 1) // initialize if doesn't exist
		ErrorHandler(err)

		gifSeqValue = 1
	}

	groupSeq = groupSeqValue
	gifSeq = gifSeqValue
}
コード例 #20
0
ファイル: redis_test.go プロジェクト: hiromaily/golibs
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//EXPIRE(key, seconds), TTL(key), INFO
//-----------------------------------------------------------------------------
func TestCommonUsingDo(t *testing.T) {
	//tu.SkipLog(t)

	sleepS := 2

	c := GetRedis().Conn

	c.Do("MSET", "key1", 20, "key2", 30)
	c.Do("HMSET", "key3:subkey1", "field1", 1, "field2", 2)
	c.Do("HMSET", "key3:subkey2", "field1", 99, "field2", 100)

	val, err := redis.Int(c.Do("GET", "key1"))
	if err != nil {
		t.Errorf("key1 is 10: value is %v, error is %s", val, err)
	}

	fields, err := redis.Ints(c.Do("HMGET", "key3:subkey1", "field1", "field2"))
	if err != nil {
		t.Errorf("field1 should be 1, field2 should be 1 but result is %#v, error is %s", fields, err)
	}

	//EXPIRE
	c.Do("EXPIRE", "key1", sleepS)
	c.Do("EXPIRE", "key3:subkey1", sleepS)

	//TTL
	s, err := redis.Int(c.Do("TTL", "key1"))
	if err != nil {
		t.Errorf("redis.Int(c.Do(\"TTL\", \"key1\")) error : %s", err)
	}
	lg.Debugf("TTL is %v", s)

	//sleep
	time.Sleep(time.Duration(sleepS+1) * time.Second)

	s, _ = redis.Int(c.Do("TTL", "key1"))
	lg.Debugf("TTL is %v", s)

	//It can't access
	val, err = redis.Int(c.Do("GET", "key1"))
	if err == nil {
		t.Errorf("key1 has already expired: value is %v", val)
	}

	//It can't access
	//TODO:somehow it can access. but value is 0
	fields, err = redis.Ints(c.Do("HMGET", "key3:subkey1", "field1", "field2"))
	//if err == nil {
	if err != nil || fields[0] != 0 || fields[1] != 0 {
		t.Errorf("key3:subkey1 has already expired: value is %+v", fields)
	}

	//It's OK.
	fields, err = redis.Ints(c.Do("HMGET", "key3:subkey2", "field1", "field2"))
	if err != nil {
		//if err != nil || fields[0] != 99 || fields[1] != 100 {
		t.Errorf("field1 should be 99, field2 should be 100 but result is %#v", fields)
	}
}
コード例 #21
0
ファイル: cache_suite_test.go プロジェクト: warmfusion/cache
func assertMatchedMetrics(matchingMetrics []string) {
	It("should be properly counted", func() {
		filter.UpdateProcessingMetrics()
		Expect(int(filter.TotalMetricsReceived.Count())).To(Equal(len(matchingMetrics)))
		Expect(int(filter.ValidMetricsReceived.Count())).To(Equal(len(matchingMetrics)))
		Expect(int(filter.MatchingMetricsReceived.Count())).To(Equal(len(matchingMetrics)))
	})

	It("should appear in cache", func() {
		c := db.Pool.Get()
		defer c.Close()

		for _, metric := range matchingMetrics {
			dbKey := filter.GetMetricDbKey(metric)
			count, err := redis.Int(c.Do("ZCOUNT", dbKey, "-inf", "+inf"))
			Expect(err).ShouldNot(HaveOccurred())
			Expect(count).To(Equal(1))
		}
	})

	It("should have correct retention", func() {
		c := db.Pool.Get()
		defer c.Close()

		for _, metric := range matchingMetrics {
			retention := 120
			if strings.HasPrefix(metric, "Simple") {
				retention = 60
			} else if strings.HasSuffix(metric, "suf") {
				retention = 1200
			}
			dbKey := filter.GetMetricRetentionDbKey(metric)
			result, err := redis.Int(c.Do("GET", dbKey))
			Expect(err).ShouldNot(HaveOccurred())
			Expect(result).To(Equal(retention))
		}
	})

	It("should have timestamp rounded to nearest retention", func() {
		c := db.Pool.Get()
		defer c.Close()

		for _, metric := range matchingMetrics {
			timestamp := "1234567920"
			if strings.HasPrefix(metric, "Simple") {
				timestamp = "1234567920"
			} else if strings.HasSuffix(metric, "suf") {
				timestamp = "1234568400"
			}
			dbKey := filter.GetMetricDbKey(metric)
			values, err := redis.Strings(c.Do("ZRANGE", dbKey, 0, -1, "WITHSCORES"))
			Expect(err).ShouldNot(HaveOccurred())
			Expect(len(values)).To(Equal(2))
			Expect(values[1]).To(Equal(timestamp))
		}
	})

}
コード例 #22
0
ファイル: fake_test.go プロジェクト: gmlexx/redigomock
func TestZadd(t *testing.T) {
	c := NewFakeRedis()
	c.Do("ZADD", "foo", 4, "four")
	c.Do("ZADD", "foo", 3, "three")
	assertInt(t, must(redis.Int(c.Do("ZADD", "foo", 2, "two", 1, "one", 0, "zero"))), 3)
	assertStrings(t, must(redis.Strings(c.Do("ZRANGE", "foo", 0, -1))).([]string), []string{"zero", "one", "two", "three", "four"}, false)
	assertInt(t, must(redis.Int(c.Do("ZADD", "foo", 7, "zero", 1, "one", 5, "five"))), 1)
	assertStrings(t, must(redis.Strings(c.Do("ZRANGE", "foo", 0, -1))).([]string), []string{"one", "two", "three", "four", "five", "zero"}, false)
}
コード例 #23
0
// Test ZREM
func TestSortedSetRem(t *testing.T) {
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	s.ZAdd("z", 1, "one")
	s.ZAdd("z", 2, "two")
	s.ZAdd("z", 2, "zwei")

	// Simple delete
	{
		b, err := redis.Int(c.Do("ZREM", "z", "two", "zwei", "nosuch"))
		ok(t, err)
		equals(t, 2, b)
		assert(t, s.Exists("z"), "key is there")
	}
	// Delete the last member
	{
		b, err := redis.Int(c.Do("ZREM", "z", "one"))
		ok(t, err)
		equals(t, 1, b)
		assert(t, !s.Exists("z"), "key is gone")
	}
	// Nonexistent key
	{
		b, err := redis.Int(c.Do("ZREM", "nosuch", "member"))
		ok(t, err)
		equals(t, 0, b)
	}

	// Direct
	{
		s.ZAdd("z2", 1, "one")
		s.ZAdd("z2", 2, "two")
		s.ZAdd("z2", 2, "zwei")
		gone, err := s.ZRem("z2", "two")
		ok(t, err)
		assert(t, gone, "member gone")
		members, err := s.ZMembers("z2")
		ok(t, err)
		equals(t, []string{"one", "zwei"}, members)
	}

	// Error cases
	{
		_, err = redis.String(c.Do("ZREM"))
		assert(t, err != nil, "ZREM error")
		_, err = redis.String(c.Do("ZREM", "set"))
		assert(t, err != nil, "ZREM error")
		// Wrong type of key
		s.Set("str", "value")
		_, err = redis.Int(c.Do("ZREM", "str", "aap"))
		assert(t, err != nil, "ZREM error")
	}
}
コード例 #24
0
ファイル: fake_test.go プロジェクト: gmlexx/redigomock
func TestSadd(t *testing.T) {
	c := NewFakeRedis()
	assertInt(t, must(redis.Int(c.Do("SADD", "foo", "member1"))), 1)
	assertInt(t, must(redis.Int(c.Do("SADD", "foo", "member1"))), 0)
	assertStrings(t, must(redis.Strings(c.Do("SMEMBERS", "foo"))).([]string), []string{"member1"}, true)
	assertInt(t, must(redis.Int(c.Do("SADD", "foo", "member2", "member3"))), 2)
	assertStrings(t, must(redis.Strings(c.Do("SMEMBERS", "foo"))).([]string), []string{"member1", "member2", "member3"}, true)
	assertInt(t, must(redis.Int(c.Do("SADD", "foo", "member3", "member4"))), 1)
	assertStrings(t, must(redis.Strings(c.Do("SMEMBERS", "foo"))).([]string), []string{"member1", "member2", "member3", "member4"}, true)
}
コード例 #25
0
ファイル: main.go プロジェクト: Catorpilor/Redis-in-action
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)
		}
	}

}
コード例 #26
0
func checkDB() {

	conn, err := redis.Dial("tcp", *host+":"+*port)
	if err != nil {
		fmt.Println(err)
		return
	}
	sumsize := 0
	for i := *minid; i <= *maxid; i++ {
		ui := uint64(i)
		userInfoName := GetUserInfoName(ui)
		cin := GetUserChatInBoxName(ui)
		cout := GetUserChatOutBoxName(ui)

		n, err := conn.Do("GET", userInfoName)

		if err != nil {
			panic(err)

		}
		if n == nil {
			panic(n)
		}

		user := UserFromRedis1(n.([]byte))
		n, err = redis.Int(conn.Do("LLEN", cin))

		if err != nil {
			panic(err)

		}
		insize := n.(int)

		n, err = redis.Int(conn.Do("LLEN", cout))

		if err != nil {
			panic(err)

		}
		outsize := n.(int)

		if insize != outsize {
			panic("insize != outsize")
		}
		if 5*len(user.UserMap) != outsize {
			panic("insize != outsize")
		}
		//fmt.Println(outsize, insize, 5 * len(user.UserMap))
		sumsize += insize
	}

	fmt.Println("success", sumsize)

}
コード例 #27
0
ファイル: fake_test.go プロジェクト: gmlexx/redigomock
func TestZRemRangeByScore(t *testing.T) {
	c := NewFakeRedis()
	c.Do("ZADD", "foo", 0, "zero")
	c.Do("ZADD", "foo", 2, "two")
	c.Do("ZADD", "foo", 4, "four")
	assertInt(t, must(redis.Int(c.Do("ZREMRANGEBYSCORE", "foo", 5, 10))), 0)
	assertStrings(t, must(redis.Strings(c.Do("ZRANGE", "foo", 0, -1))).([]string), []string{"zero", "two", "four"}, false)
	assertInt(t, must(redis.Int(c.Do("ZREMRANGEBYSCORE", "foo", 1, 3))), 1)
	assertStrings(t, must(redis.Strings(c.Do("ZRANGE", "foo", 0, -1))).([]string), []string{"zero", "four"}, false)
	assertInt(t, must(redis.Int(c.Do("ZREMRANGEBYSCORE", "foo", 0, 4))), 2)
	assertStrings(t, must(redis.Strings(c.Do("ZRANGE", "foo", 0, -1))).([]string), []string{}, false)
}
コード例 #28
0
ファイル: cmd_hash_test.go プロジェクト: nodephp/ledisdb
func TestHashM(t *testing.T) {
	startTestApp()

	c := getTestConn()
	defer c.Close()

	key := []byte("b")
	if ok, err := redis.String(c.Do("hmset", key, 1, 1, 2, 2, 3, 3)); err != nil {
		t.Fatal(err)
	} else if ok != OK {
		t.Fatal(ok)
	}

	if n, err := redis.Int(c.Do("hlen", key)); err != nil {
		t.Fatal(err)
	} else if n != 3 {
		t.Fatal(n)
	}

	if v, err := redis.MultiBulk(c.Do("hmget", key, 1, 2, 3, 4)); err != nil {
		t.Fatal(err)
	} else {
		if err := testHashArray(v, 1, 2, 3, 0); err != nil {
			t.Fatal(err)
		}
	}

	if n, err := redis.Int(c.Do("hdel", key, 1, 2, 3, 4)); err != nil {
		t.Fatal(err)
	} else if n != 3 {
		t.Fatal(n)
	}

	if n, err := redis.Int(c.Do("hlen", key)); err != nil {
		t.Fatal(err)
	} else if n != 0 {
		t.Fatal(n)
	}

	if v, err := redis.MultiBulk(c.Do("hmget", key, 1, 2, 3, 4)); err != nil {
		t.Fatal(err)
	} else {
		if err := testHashArray(v, 0, 0, 0, 0); err != nil {
			t.Fatal(err)
		}
	}

	if n, err := redis.Int(c.Do("hlen", key)); err != nil {
		t.Fatal(err)
	} else if n != 0 {
		t.Fatal(n)
	}
}
コード例 #29
0
ファイル: redigolock_test.go プロジェクト: vube/redigolock
// Test that our locks are actually preventing race conditions by doing a
// non-atomic Redis operation surrounded by a lock
func Test_Increment(t *testing.T) {
	key := "Test_Increment"
	wg := new(sync.WaitGroup)

	wg.Add(100)
	for i := 0; i < 100; i++ {
		go func() {
			defer wg.Done()
			conn, err := redigo.Dial("tcp", RedisHost)

			if err != nil {
				t.Errorf("redigo.Dial failure due to '%s'", err)
				return
			}

			lock := New(conn, key, 2000, DefaultAutoExpire, DefaultHold, 5)

			status, err := lock.Lock()

			if status {
				// arbitrary distributed non-atomic operation
				v, _ := redigo.Int(conn.Do("GET", key))
				v++
				time.Sleep(100000)
				conn.Do("SET", key, v)
			} else {
				if err != nil {
					t.Errorf("lock operation failure due to '%s", err)
				} else {
					t.Error("timed out during lock contention")
				}
			}

			lock.UnlockIfLocked()
		}()
	}

	wg.Wait()

	conn, err := redigo.Dial("tcp", RedisHost)

	if err != nil {
		t.Errorf("redigo.Dial failure due to '%s'", err)
	}

	v, _ := redigo.Int(conn.Do("GET", key))

	if v != 100 {
		t.Error("increment miscalculation")
	}

	conn.Do("DEL", key)
}
コード例 #30
0
func (s SidekiqPlugin) FetchMetrics() (map[string]float64, error) {
	c, err := redis.Dial("tcp", s.Target)
	if err != nil {
		return nil, err
	}
	defer c.Close()

	prefix := ""
	if s.Namespace != "" {
		prefix = s.Namespace + ":"
	}

	_, err = c.Do("SELECT", s.Database)
	if err != nil {
		return nil, err
	}

	queues, err := redis.Strings(c.Do("SMEMBERS", prefix+"queues"))
	if err != nil {
		return nil, err
	}

	metrics := make(map[string]float64)

	for _, queue := range queues {
		enqueued, err := redis.Int(c.Do("LLEN", prefix+"queue:"+queue))
		if err != nil {
			return nil, err
		}
		metrics["queue."+queue] = float64(enqueued)
	}

	retries, err := redis.Int(c.Do("ZCARD", prefix+"retries"))
	if err != nil {
		return nil, err
	}
	metrics["retries"] = float64(retries)

	schedule, err := redis.Int(c.Do("ZCARD", prefix+"schedule"))
	if err != nil {
		return nil, err
	}
	metrics["schedule"] = float64(schedule)

	dead, err := redis.Int(c.Do("ZCARD", prefix+"dead"))
	if err != nil {
		return nil, err
	}
	metrics["dead"] = float64(dead)

	return metrics, nil
}