Пример #1
0
func TestDiscardTransaction(t *testing.T) {
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	s.Set("aap", "noot")

	b, err := redis.String(c.Do("MULTI"))
	ok(t, err)
	equals(t, "OK", b)

	b, err = redis.String(c.Do("SET", "aap", "mies"))
	ok(t, err)
	equals(t, "QUEUED", b)

	// Not committed
	s.CheckGet(t, "aap", "noot")

	v, err := redis.String(c.Do("DISCARD"))
	ok(t, err)
	equals(t, "OK", v)

	// TX didn't get executed
	s.CheckGet(t, "aap", "noot")
}
Пример #2
0
func (u *User) Register(args *User_RegisterArgs, reply *Reply) error {
	if args.Psw == "" {
		reply.Code = com.E_AgentPasswordCannotBeNull
	} else {
		accountkey := k_account_user_ + args.Account
		account, _ := redis.String(u.c.Do("GET", accountkey))
		//	exists, _ := redis.Bool(u.c.Do("EXISTS", accountkey))
		//	if !exists {
		if account == "" {
			// create id
			u.c.Do("INCR", k_account_count)
			id, _ := redis.String(u.c.Do("GET", k_account_count))

			// save account
			u.c.Do("SET", accountkey, id)
			u.c.Do("SADD", k_account_userlist, id)

			// save user
			userkey := k_user_ + string(id)
			u.c.Do("HSET", userkey, k_psw, args.Psw)
			u.c.Do("HSET", userkey, k_coin, 0)
			u.c.Do("HSET", userkey, k_nickname, "nickname")

			reply.Code = com.E_Success
			log.Debug("Register success")
		} else {
			reply.Code = com.E_AgentAccountExist
			log.Debug("E_AgentAccountExist")
		}
	}
	return nil
}
Пример #3
0
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")
	}
}
Пример #4
0
func GetDeviceUsers(deviceId int64) ([]int64, error) {
	r := Redix[_GetDeviceUsers]
	RedixMu[_GetDeviceUsers].Lock()
	defer RedixMu[_GetDeviceUsers].Unlock()
	user, err := redis.String(r.Do("hget", RedisDeviceUsers, deviceId))
	if err != nil {
		return nil, err
	}
	host, err2 := redis.String(r.Do("hget", "user:family", user))
	//如果找不到host,说明此用户是孤儿,那么只返回此设备的直接关联用户
	//如果找到host,就返回此设备直接关联用户所属家庭所有成员
	if host == "" || err2 != nil {
		bindedIds := make([]int64, 0, 1)
		u_id, _ := strconv.ParseInt(user, 10, 64)
		bindedIds = append(bindedIds, int64(u_id))
		return bindedIds, nil
	} else {
		mems, _ := redis.Strings(r.Do("smembers", fmt.Sprintf("family:%v", host)))
		bindedIds := make([]int64, 0, len(mems))
		for _, m := range mems {
			u_id, err := strconv.ParseInt(m, 10, 64)
			if err == nil {
				bindedIds = append(bindedIds, int64(u_id))
			}
		}
		return bindedIds, nil
	}
}
Пример #5
0
func TestRpop(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")

	// Simple pops.
	{
		el, err := redis.String(c.Do("RPOP", "l"))
		ok(t, err)
		equals(t, "mies", el)

		el, err = redis.String(c.Do("RPOP", "l"))
		ok(t, err)
		equals(t, "noot", el)

		el, err = redis.String(c.Do("RPOP", "l"))
		ok(t, err)
		equals(t, "aap", el)

		// Last element has been popped. Key is gone.
		i, err := redis.Int(c.Do("EXISTS", "l"))
		ok(t, err)
		equals(t, 0, i)

		// Can pop non-existing keys just fine.
		v, err := c.Do("RPOP", "l")
		ok(t, err)
		equals(t, nil, v)
	}
}
Пример #6
0
func AddUser(user *UserInfo) (rs uint32, err error) {
	conn := userRedisPool.Get()
	defer conn.Close()
	var nkey string = fmt.Sprintf("n_%s", user.Name)
	var exist bool
	var seq int64
	if seq, err = redis.Int64(conn.Do("incr", UserIdSeq)); err != nil {
		return
	}
	if exist, err = redis.Bool(conn.Do("exists", nkey)); err != nil {
		return
	}
	if exist {
		err = UserExists
		return
	}
	var buf = make([]byte, 4)
	binary.LittleEndian.PutUint32(buf, uint32(seq))
	if _, err = redis.String(conn.Do("set", nkey, buf)); err != nil {
		return
	}
	rs = uint32(seq)
	user.Id = rs
	key := fmt.Sprintf("u%d", rs)
	var val []byte
	if val, err = json.Marshal(user); err != nil {
		return
	}
	if _, err = redis.String(conn.Do("set", key, val)); err != nil {
		return
	}
	return
}
Пример #7
0
// Return a JSON with the ids and names of the Pingdom checks
func getJsonChecks(redisResponse []interface{}) []byte {
	conn := redisPool.Get() // Redis connection to get the names for the ids

	checks := make([]CheckType, len(redisResponse))

	for k, _ := range redisResponse {
		v := ""
		redisResponse, _ = redis.Scan(redisResponse, &v)
		id, _ := strconv.ParseInt(v, 10, 64)

		// Get the name corresponding to the id
		n, err := redis.String(conn.Do("GET", "check:"+v))
		for {
			if err == nil {
				break
			} else {
				log.Printf("Redis error in GET check: %s\n", err)
				n, err = redis.String(conn.Do("GET", "check:"+v))
			}
		}

		checks[k] = CheckType{id, n}
	}
	conn.Close()
	b, _ := json.MarshalIndent(Checks{checks}, "", "  ")
	return b
}
Пример #8
0
func main() {
	c, err := redis.Dial("tcp", ":6379")
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	// SET command only lets you have one value for the key
	c.Do("SET", "MY_KEY", "MY_VALUE")

	// HSET lets you have multiple fields and values
	c.Do("HSET", "myhash", "field1", "Hello")
	// myhash = { field1 : "Hello" }

	val1, err := redis.String(c.Do("GET", "MY_KEY"))
	if err != nil {
		fmt.Println("key not found")
	}
	fmt.Println(val1)
	// MY_VALUE

	val2, err := redis.String(c.Do("HGET", "myhash", "field1"))
	if err != nil {
		fmt.Println("key not found")
	}
	fmt.Println(val2)
	// Hello
}
Пример #9
0
func (c *client) QPeek(queueName string, count int) ([]job, error) {
	conn, err := c.get()
	if err != nil {
		return nil, err
	}

	reply, err := redis.Values(conn.Do("QPEEK", queueName, count))
	if err != nil {
		return nil, err
	}

	result := make([]job, 0, len(reply))
	for _, v := range reply {
		if value, err := redis.Values(v, nil); err != nil {
			return nil, err
		} else {
			queueName, err := redis.String(value[0], nil)
			id, err := redis.String(value[1], err)
			data, err := redis.Bytes(value[2], err)
			if err != nil {
				return nil, err
			}
			result = append(result, job{QueueName: queueName, Id: id, Body: data})
		}
	}
	return result, nil
}
Пример #10
0
func Migrate(addr, toIp string, toPort int, key string, timeout int) (string, error) {
	inner := func(addr, toIp string, toPort int, key string, timeout int) (string, error) {
		conn, err := dial(addr)
		if err != nil {
			return "", ErrConnFailed
		}
		defer conn.Close()

		resp, err := redis.String(conn.Do("migrate", toIp, toPort, key, 0, timeout))
		if err != nil && strings.Contains(err.Error(), "BUSYKEY") {
			log.Warningf("Migrate", "Found BUSYKEY '%s', will overwrite it.", key)
			resp, err = redis.String(conn.Do("migrate", toIp, toPort, key, 0, timeout, "replace"))
		}
		if err != nil {
			return "", err
		}
		return resp, nil
	}
	retry := NUM_RETRY
	var err error
	var resp string
	for retry > 0 {
		resp, err = inner(addr, toIp, toPort, key, timeout)
		if err == nil {
			return resp, nil
		}
		retry--
	}
	return "", err
}
Пример #11
0
func TestSingleKeyRedisCmd(t *testing.T) {
	InitEnv()
	c, err := redis.Dial("tcp", "localhost:19000")
	if err != nil {
		t.Fatal(err)
	}
	defer c.Close()

	_, err = c.Do("SET", "foo", "bar")
	if err != nil {
		t.Error(err)
	}

	if got, err := redis.String(c.Do("get", "foo")); err != nil || got != "bar" {
		t.Error("'foo' has the wrong value")
	}

	_, err = c.Do("SET", "bar", "foo")
	if err != nil {
		t.Error(err)
	}

	if got, err := redis.String(c.Do("get", "bar")); err != nil || got != "foo" {
		t.Error("'bar' has the wrong value")
	}
}
Пример #12
0
func ClusterFailover(addr string, rs *topo.ReplicaSet) (string, error) {
	conn, err := dial(addr)
	if err != nil {
		return "", ErrConnFailed
	}
	defer conn.Close()

	// 先正常Failover试试,如果主挂了再试试Force
	resp, err := redis.String(conn.Do("cluster", "failover"))
	if err != nil {
		if strings.HasPrefix(err.Error(), "ERR Master is down or failed") {
			resp, err = redis.String(conn.Do("cluster", "failover", "force"))
		}
		if err != nil {
			return "", err
		}
	}

	// 30s
	for i := 0; i < 30; i++ {
		info, err := FetchInfo(addr, "Replication")
		if err != nil {
			return resp, err
		}
		if info.Get("role") == "slave" {
			time.Sleep(1 * time.Second)
		} else {
			break
		}
	}
	return resp, nil
}
Пример #13
0
// 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
}
Пример #14
0
func TestSelect(t *testing.T) {
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	_, err = redis.String(c.Do("SET", "foo", "bar"))
	ok(t, err)

	_, err = redis.String(c.Do("SELECT", "5"))
	ok(t, err)

	_, err = redis.String(c.Do("SET", "foo", "baz"))
	ok(t, err)

	// Direct access.
	got, err := s.Get("foo")
	ok(t, err)
	equals(t, "bar", got)
	s.Select(5)
	got, err = s.Get("foo")
	ok(t, err)
	equals(t, "baz", got)

	// Another connection should have its own idea of the db:
	c2, err := redis.Dial("tcp", s.Addr())
	ok(t, err)
	v, err := redis.String(c2.Do("GET", "foo"))
	ok(t, err)
	equals(t, "bar", v)
}
Пример #15
0
func TestConnMux(t *testing.T) {
	c, err := redistest.Dial()
	if err != nil {
		t.Fatalf("error connection to database, %v", err)
	}
	m := redisx.NewConnMux(c)
	defer m.Close()

	c1 := m.Get()
	c2 := m.Get()
	c1.Send("ECHO", "hello")
	c2.Send("ECHO", "world")
	c1.Flush()
	c2.Flush()
	s, err := redis.String(c1.Receive())
	if err != nil {
		t.Fatal(err)
	}
	if s != "hello" {
		t.Fatalf("echo returned %q, want %q", s, "hello")
	}
	s, err = redis.String(c2.Receive())
	if err != nil {
		t.Fatal(err)
	}
	if s != "world" {
		t.Fatalf("echo returned %q, want %q", s, "world")
	}
	c1.Close()
	c2.Close()
}
Пример #16
0
func (s *testProxyRouterSuite) TestAuthCmd(c *C) {
	if len(proxyAuth) > 0 {
		cc, err := redis.Dial("tcp", proxyAddr)
		c.Assert(err, IsNil)

		_, err = cc.Do("SET", "foo", "bar")
		c.Assert(err, NotNil)
		c.Assert(err, ErrorMatches, "ERR NOAUTH Authentication required")
	} else {
		cc, err := redis.Dial("tcp", proxyAddr)
		c.Assert(err, IsNil)

		_, err = cc.Do("SET", "foo", "bar")
		c.Assert(err, IsNil)
	}

	cc, err := redis.Dial("tcp", proxyAddr)
	c.Assert(err, IsNil)

	ok, err := redis.String(cc.Do("AUTH", proxyAuth))
	c.Assert(err, IsNil)
	c.Assert(ok, Equals, "OK")

	_, err = cc.Do("SET", "foo", "bar")
	c.Assert(err, IsNil)

	ok, err = redis.String(cc.Do("AUTH", "Wrong-auth-key"))
	c.Assert(err, NotNil)
	c.Assert(err, ErrorMatches, "ERR invalid auth")
	c.Assert(ok, Equals, "")

	s.s1.store.Reset()
	s.s2.store.Reset()
}
Пример #17
0
// Test simple multi/exec block.
func TestSimpleTransaction(t *testing.T) {
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	b, err := redis.String(c.Do("MULTI"))
	ok(t, err)
	equals(t, "OK", b)

	b, err = redis.String(c.Do("SET", "aap", 1))
	ok(t, err)
	equals(t, "QUEUED", b)

	// Not set yet.
	equals(t, false, s.Exists("aap"))

	v, err := redis.Values(c.Do("EXEC"))
	ok(t, err)
	equals(t, 1, len(redis.Args(v)))
	equals(t, "OK", v[0])

	// SET should be back to normal mode
	b, err = redis.String(c.Do("SET", "aap", 1))
	ok(t, err)
	equals(t, "OK", b)
}
Пример #18
0
func TestTxWatch(t *testing.T) {
	// Watch with no error.
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	s.Set("one", "two")
	b, err := redis.String(c.Do("WATCH", "one"))
	ok(t, err)
	equals(t, "OK", b)

	b, err = redis.String(c.Do("MULTI"))
	ok(t, err)
	equals(t, "OK", b)

	b, err = redis.String(c.Do("GET", "one"))
	ok(t, err)
	equals(t, "QUEUED", b)

	v, err := redis.Values(c.Do("EXEC"))
	ok(t, err)
	equals(t, 1, len(v))
	equals(t, []byte("two"), v[0])
}
Пример #19
0
func TestTxQueueErr(t *testing.T) {
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	b, err := redis.String(c.Do("MULTI"))
	ok(t, err)
	equals(t, "OK", b)

	b, err = redis.String(c.Do("SET", "aap", "mies"))
	ok(t, err)
	equals(t, "QUEUED", b)

	// That's an error!
	_, err = redis.String(c.Do("SET", "aap"))
	assert(t, err != nil, "do SET error")

	// Thisone is ok again
	b, err = redis.String(c.Do("SET", "noot", "vuur"))
	ok(t, err)
	equals(t, "QUEUED", b)

	_, err = redis.String(c.Do("EXEC"))
	assert(t, err != nil, "do EXEC error")

	// Didn't get EXECed
	equals(t, false, s.Exists("aap"))
}
Пример #20
0
func (rs *RedisStore) conn() (conn redis.Conn, err error) {
	if rs.redis == nil {
		c, err2 := redis.Dial("tcp", rs.addr)
		if err2 != nil {
			return nil, err2
		}
		if rs.logger != nil {
			c = redis.NewLoggingConn(c, rs.logger, rs.prefix)
		}
		if rs.password != "" {
			_, authErr := redis.String(c.Do("AUTH", rs.password))
			if authErr != nil {
				err = authErr
				return
			}
		}
		if rs.db != "" {
			_, selDbErr := redis.String(c.Do("SELECT", rs.db))
			if selDbErr != nil {
				err = selDbErr
				return
			}
		}
		rs.redis = c
	}
	return rs.redis, nil
}
Пример #21
0
func TestSetThenGet(t *testing.T) {
	c := NewFakeRedis()
	redis.String(c.Do("SET", "foo", "bar"))
	r := must(redis.String(c.Do("GET", "foo"))).(string)
	if r != "bar" {
		t.Errorf("Expect 'bar'. Got '%s'", r)
	}
}
Пример #22
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")
	}
}
Пример #23
0
func ResetUserDeviceToken(appid int64, uid int64, device_token string, ng_device_token string, xg_device_token string) error {
	conn := redis_pool.Get()
	defer conn.Close()

	key := fmt.Sprintf("users_%d_%d", appid, uid)
	if len(device_token) > 0 {
		token, err := redis.String(conn.Do("HGET", key, "apns_device_token"))
		if err != nil {
			log.Info("hget err:", err)
			return err
		}
		if token != device_token {
			log.Infof("reset apns token:%s device token:%s\n", token, device_token)
			return nil
		}
		_, err = conn.Do("HDEL", key, "apns_device_token", "apns_timestamp")
		if err != nil {
			log.Info("hdel err:", err)
			return err
		}
	}

	if len(ng_device_token) > 0 {
		token, err := redis.String(conn.Do("HGET", key, "ng_device_token"))
		if err != nil {
			log.Info("hget err:", err)
			return err
		}
		if token != ng_device_token {
			log.Infof("reset ng token:%s device token:%s\n", token, ng_device_token)
			return nil
		}
		_, err = conn.Do("HDEL", key, "ng_device_token", "ng_timestamp")
		if err != nil {
			log.Info("hdel err:", err)
			return err
		}
	}

	if len(xg_device_token) > 0 {
		token, err := redis.String(conn.Do("HGET", key, "xg_device_token"))
		if err != nil {
			log.Info("hget err:", err)
			return err
		}
		if token != xg_device_token {
			log.Infof("reset xg token:%s device token:%s\n", token, ng_device_token)
			return nil
		}
		_, err = conn.Do("HDEL", key, "xg_device_token", "xg_timestamp")
		if err != nil {
			log.Info("hdel err:", err)
			return err
		}
	}
	return nil
}
Пример #24
0
// Test simple GET/SET keys
func TestString(t *testing.T) {
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	// SET command
	{
		v, err := redis.String(c.Do("SET", "foo", "bar"))
		ok(t, err)
		equals(t, "OK", v)
	}

	// GET command
	{
		v, err := redis.String(c.Do("GET", "foo"))
		ok(t, err)
		equals(t, "bar", v)
	}

	// Query server directly.
	{
		got, err := s.Get("foo")
		ok(t, err)
		equals(t, "bar", got)
	}

	// Use Set directly
	{
		ok(t, s.Set("aap", "noot"))
		s.CheckGet(t, "aap", "noot")
		v, err := redis.String(c.Do("GET", "aap"))
		ok(t, err)
		equals(t, "noot", v)
		s.CheckGet(t, "aap", "noot")
		// Re-set.
		ok(t, s.Set("aap", "noot2"))
	}

	// GET a non-existing key. Should be nil.
	{
		b, err := c.Do("GET", "reallynosuchkey")
		ok(t, err)
		equals(t, nil, b)
	}

	// Wrong usage.
	{
		_, err := c.Do("HSET", "wim", "zus", "jet")
		ok(t, err)
		_, err = c.Do("GET", "wim")
		assert(t, err != nil, "no GET error")
	}
}
Пример #25
0
// Test ZSCORE
func TestSortedSetScore(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 case
	{
		b, err := redis.Float64(c.Do("ZSCORE", "z", "two"))
		ok(t, err)
		equals(t, 2.0, b)
	}
	// no such member
	{
		b, err := c.Do("ZSCORE", "z", "nosuch")
		ok(t, err)
		equals(t, nil, b)
	}
	// no such key
	{
		b, err := c.Do("ZSCORE", "nosuch", "nosuch")
		ok(t, err)
		equals(t, nil, b)
	}

	// Direct
	{
		s.ZAdd("z2", 1, "one")
		s.ZAdd("z2", 2, "two")
		score, err := s.ZScore("z2", "two")
		ok(t, err)
		equals(t, 2.0, score)
	}

	// Error cases
	{
		_, err = redis.String(c.Do("ZSCORE"))
		assert(t, err != nil, "ZSCORE error")
		_, err = redis.String(c.Do("ZSCORE", "key"))
		assert(t, err != nil, "ZSCORE error")
		_, err = redis.String(c.Do("ZSCORE", "too", "many", "arguments"))
		assert(t, err != nil, "ZSCORE error")
		// Wrong type of key
		s.Set("str", "value")
		_, err = redis.Int(c.Do("ZSCORE", "str", "aap"))
		assert(t, err != nil, "ZSCORE error")
	}
}
Пример #26
0
func TestRedisPop(t *testing.T) {
	Convey("Test Redis Pop Api", t, func() {
		rpl, err := redis.Values(conn.Do("QPOP", "foo/x"))
		So(err, ShouldBeNil)
		v, err := redis.String(rpl[0], err)
		So(err, ShouldBeNil)
		So(v, ShouldEqual, "1")
		id, err := redis.String(rpl[1], err)
		So(err, ShouldBeNil)
		So(id, ShouldEqual, "foo/x/0")
	})
}
Пример #27
0
func GetRedisInfo(addr string, section string, auth string) (string, error) {
	c, err := newRedisConn(addr, auth)
	if err != nil {
		return "", errors.Trace(err)
	}
	defer c.Close()

	if len(section) > 0 {
		return redis.String(c.Do("INFO", section))
	} else {
		return redis.String(c.Do("INFO"))
	}
}
Пример #28
0
func c_redis_counters(server string, db int) (opentsdb.MultiDataPoint, error) {
	var md opentsdb.MultiDataPoint
	conn, err := redis.Dial("tcp", server, redis.DialDatabase(db))
	if err != nil {
		return md, slog.Wrap(err)
	}
	defer conn.Close()

	//do a dance to detect proper hscan command for ledis or redis
	hscanCmd := "XHSCAN"
	info, err := redis.String(conn.Do("info", "server"))
	if err != nil {
		return md, slog.Wrap(err)
	}
	if strings.Contains(info, "redis_version") {
		hscanCmd = "HSCAN"
	}

	cursor := "0"
	for {
		vals, err := redis.Values(conn.Do(hscanCmd, collect.RedisCountersKey, cursor))
		if err != nil {
			return md, slog.Wrap(err)
		}
		if len(vals) != 2 {
			return md, fmt.Errorf("Unexpected number of values")
		}
		cursor, err = redis.String(vals[0], nil)
		if err != nil {
			return md, slog.Wrap(err)
		}
		pairs, err := redis.StringMap(vals[1], nil)
		if err != nil {
			return md, slog.Wrap(err)
		}
		for key, val := range pairs {
			ak := models.AlertKey(key)

			v, err := strconv.Atoi(val)
			if err != nil {
				slog.Errorf("Invalid counter value: %s", val)
				continue
			}
			Add(&md, ak.Name(), v, ak.Group(), metadata.Counter, metadata.Count, "")
		}
		if cursor == "" || cursor == "0" {
			break
		}
	}
	return md, nil
}
Пример #29
0
func TestQuit(t *testing.T) {
	s, err := Run()
	ok(t, err)
	defer s.Close()
	c, err := redis.Dial("tcp", s.Addr())
	ok(t, err)

	v, err := redis.String(c.Do("QUIT"))
	ok(t, err)
	equals(t, "OK", v)

	v, err = redis.String(c.Do("PING"))
	assert(t, err != nil, "QUIT closed the client")
}
Пример #30
0
// GetValues queries redis for keys prefixed by prefix.
func (c *Client) GetValues(keys []string) (map[string]string, error) {
	// Ensure we have a connected redis client
	rClient, err := c.connectedClient()
	if err != nil && err != redis.ErrNil {
		return nil, err
	}

	vars := make(map[string]string)
	for _, key := range keys {
		key = strings.Replace(key, "/*", "", -1)
		value, err := redis.String(rClient.Do("GET", key))
		if err == nil {
			vars[key] = value
			continue
		}

		if err != redis.ErrNil {
			return vars, err
		}

		if key == "/" {
			key = "/*"
		} else {
			key = fmt.Sprintf("%s/*", key)
		}

		idx := 0
		for {
			values, err := redis.Values(rClient.Do("SCAN", idx, "MATCH", key, "COUNT", "1000"))
			if err != nil && err != redis.ErrNil {
				return vars, err
			}
			idx, _ = redis.Int(values[0], nil)
			items, _ := redis.Strings(values[1], nil)
			for _, item := range items {
				var newKey string
				if newKey, err = redis.String(item, nil); err != nil {
					return vars, err
				}
				if value, err = redis.String(rClient.Do("GET", newKey)); err == nil {
					vars[newKey] = value
				}
			}
			if idx == 0 {
				break
			}
		}
	}
	return vars, nil
}