package main import ( "common" "fmt" "proto" "strconv" "time" "github.com/garyburd/redigo/redis" "github.com/gogo/protobuf/proto" ) type RedisHelper struct { redisClient *redis.Pool } var redisHelper *RedisHelper func RedisHelper_GetMe() *RedisHelper { if redisHelper == nil { redisHelper = &RedisHelper{} } return redisHelper } func (this *RedisHelper) init() { maxIdle := 1024 maxActive := 1024 // 建立连接池 this.redisClient = &redis.Pool{ MaxIdle: maxIdle, MaxActive: maxActive, IdleTimeout: 1 * time.Second, Wait: true, Dial: func() (redis.Conn, error) { con, err := redis.Dial("tcp", "127.0.0.1:6379", redis.DialPassword(""), redis.DialDatabase(int(0)), redis.DialConnectTimeout(1*time.Second), redis.DialReadTimeout(1*time.Second), redis.DialWriteTimeout(1*time.Second)) if err != nil { return nil, err } return con, nil }, } } func (this *RedisHelper) GetServerIdByType(accountId int64, st uint32) uint32 { // 从池里获取连接 rc := this.redisClient.Get() // 用完后将连接放回连接池 defer rc.Close() // 错误判断 if rc.Err() != nil { return 0 } // v, err := redis.String(rc.Do("GET", strconv.FormatInt(accountId, 10))) if err != nil { return 0 } p := &testone.CProtoRedisServer{} err = proto.UnmarshalText(v, p) fmt.Println(v) if err != nil { return 0 } if st == common.GateServer { return p.GetGateId() } if st == common.FightServer { return p.GetFightId() } if st == common.GameServer { return p.GetGameId() } return 0 } func (this *RedisHelper) SaveOrUpdateServer(accountId int64, p *testone.CProtoRedisServer) bool { // 从池里获取连接 rc := this.redisClient.Get() // 用完后将连接放回连接池 defer rc.Close() // 错误判断 if rc.Err() != nil { return false } valstr := p.String() actstr := strconv.FormatInt(accountId, 10) _, err := rc.Do("SET", actstr, valstr) if err != nil { return false } return true }