Blame view

common/db/redisproxy/redis.go 1.84 KB
436e0af4   zhangqijia   reactor: dir; Ac...
1
  package redisproxy
cad2b7f3   zhangqijia   reactor: 重构目录, 重构...
2
3
4
  
  import (
  	"github.com/garyburd/redigo/redis"
cad2b7f3   zhangqijia   reactor: 重构目录, 重构...
5
6
7
8
  	"time"
  )
  var RedisPool *redis.Pool
  
5d9cf01c   zhangqijia   plugin 热更
9
10
  //conf *conf.ServerConf
  func ConnectRedis(db int, auth, address string) error {
cad2b7f3   zhangqijia   reactor: 重构目录, 重构...
11
12
13
14
15
16
17
18
  	RedisPool = &redis.Pool{
  		//最大活跃连接数,0代表无限
  		MaxActive: 888,
  		MaxIdle: 20,
  		//闲置连接的超时时间
  		IdleTimeout: time.Second * 100,
  		//定义拨号获得连接的函数
  		Dial: func() (redis.Conn, error) {
5d9cf01c   zhangqijia   plugin 热更
19
20
21
  			option := []redis.DialOption{redis.DialDatabase(db)}
  			if auth != "" {
  				option = append(option, redis.DialPassword(auth))
cad2b7f3   zhangqijia   reactor: 重构目录, 重构...
22
  			}
5d9cf01c   zhangqijia   plugin 热更
23
  			return redis.Dial("tcp",address, option...)
cad2b7f3   zhangqijia   reactor: 重构目录, 重构...
24
25
26
27
28
29
30
31
32
  		},
  	}
  	return nil
  }
  
  func CloseRedis()  {
  	RedisPool.Close()
  }
  
29a163be   zhangqijia   fix: CreateReq ui...
33
  func redisCommand(command string, args ...interface{}) (reply interface{}, err error) {
cad2b7f3   zhangqijia   reactor: 重构目录, 重构...
34
35
  	conn := RedisPool.Get()
  	defer conn.Close()
29a163be   zhangqijia   fix: CreateReq ui...
36
37
38
  	return conn.Do(command , args...)
  }
  
8f83d322   zhangqijia   redis 管道操作
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
  
  func ExpireKey(key interface{}, ttl interface{}) (reply interface{}, err error) {
  	return redisCommand("expire", key, ttl)
  }
  
  //redis 管道操作
  func PipLine(f func(conn redis.Conn))  {
  	conn := RedisPool.Get()
  	defer conn.Close()
  	f(conn)
  }
  
  func PipLineTest()  {
  	PipLine(func(c redis.Conn) {
  		c.Send("SET", "foo", "bar")
  		c.Send("GET", "foo")
  		c.Flush()
  		//receive一次只从结果中拿出一个send的命令进行处理
  		c.Receive()        // reply from SET
  		_, _ = c.Receive() // reply from GET
  	})
  }
  
29a163be   zhangqijia   fix: CreateReq ui...
62
63
64
65
66
67
68
69
70
71
72
73
74
75
  func SETNX(args ...interface{}) (reply interface{}, err error) {
  	return redisCommand("SETNX", args...)
  }
  
  func SET(args ...interface{}) (reply interface{}, err error) {
  	return redisCommand("SET", args...)
  }
  
  func GET(args ...interface{}) (reply interface{}, err error) {
  	return redisCommand("GET", args...)
  }
  
  func HKEYS(args ...interface{}) (reply interface{}, err error) {
  	return redisCommand("HKEYS", args...)
cad2b7f3   zhangqijia   reactor: 重构目录, 重构...
76
77
78
  }
  
  func HMSET(args ...interface{})  (reply interface{}, err error) {
29a163be   zhangqijia   fix: CreateReq ui...
79
  	return redisCommand("HMSET", args...)
cad2b7f3   zhangqijia   reactor: 重构目录, 重构...
80
  }