golang操作redis

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
func DefaultPool() *redis.Pool {
	return &redis.Pool{
		MaxIdle:     8,
		MaxActive:   1,
		IdleTimeout: 100,
		Dial: func() (redis.Conn, error) {
			return redis.Dial("tcp", "localhost:6379")
		},
	}
}

func Default() *RedisQueueImpl {
	return &RedisQueueImpl{
		pool: DefaultPool(),
	}
}


type RedisQueueImpl struct {
	pool *redis.Pool
}

type Queue RedisQueueImpl

func (q *RedisQueueImpl) Brpop(queueName string, timeoutSecond int) (string, error) {

	var conn = q.pool.Get()
	defer conn.Close()
	// timeout 表示 时间
	json, err := redis.Strings(conn.Do("brpop", queueName, timeoutSecond))
	if err != nil {
		myLog.Error(err)
		return "", err
	}
	myLog.Result(json)

	if len(json) > 1 {
		return json[1], err
	}
	return "", err

}
func (q *RedisQueueImpl) Lpush(queueName string, obj []interface{}) error {
	var conn = q.pool.Get()
	defer conn.Close()
	res, err := (conn.Do("lpush", redis.Args{}.Add(queueName).AddFlat(obj)...))

	if err != nil {
		myLog.Error(err)
		return err
	}
	myLog.Result(res)
	return err
}

func (q *RedisQueueImpl) Get(obj interface{}) (string, error) {
	var conn = q.pool.Get()
	defer conn.Close()

	data, err := redis.String(conn.Do("Get", "a"))
	if err != nil {
		return "", err
	}

	// fmt.Println(data)
	return data, err

}