golang redis使用连接池

redis 基本操作

import "github.com/go-redis/redis"

var redisClient *redis.Client

redisClient = redis.NewClient(&redis.Options{
	Addr:     addr,
	Password: password,
})

if _, err := redisClient.Ping().Result(); err != nil {
	fmt.Println(err)
	os.Exit(0)
}

if flag := redisClient.SIsMember("KEY", uid).Val(); falg {
    ...    
}

redis pool

"github.com/garyburd/redigo/redis"

// redis pool
func redisPoolInit(server string, password string) *redis.Pool {
	return &redis.Pool{
		MaxIdle:     50,
		IdleTimeout: 240 * time.Second,
		MaxActive:   100,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", server)
			if err != nil {
				return nil, err
			}
			if password != "" {
				if _, err := c.Do("AUTH", password); err != nil {
					c.Close()
					return nil, err
				}
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}

UserRightReidsPool = redisPoolInit(*redisAddr, *redisPassword)

smember 替换为 sscan, 提高性能

// smember -> sscan
client := UserRightReidsPool.Get()
defer client.Close()
var err error
var all []string
cursor := "0"
for {
	res, err := redis.MultiBulk(client.Do("SSCAN", key, cursor, "count", "1000"))
	if err != nil {
		break;
	}
	cursor, err = redis.String(res[0], err)
	val, err := redis.Strings(res[1], err)
	all = append(all, val...)
	if cursor == "0" {
		break
	}
}

你可能感兴趣的:(golang,数据库)