Documentation ¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetRedisConn ¶
GetRedisConn gets the Redis connection.
Example ¶
package main import ( "log" "github.com/gomodule/redigo/redis" "github.com/northbright/redishelper" ) func main() { var err error var c redis.Conn redisAddr := ":6379" redisPassword := "" if c, err = redishelper.GetRedisConn(redisAddr, redisPassword); err != nil { log.Printf("GetRedisConn() error: %v", err) return } defer c.Close() log.Printf("Get Redis connection successfully.\n") }
Output:
func NewRedisPool ¶
func NewRedisPool(redisServer, redisPassword string, maxActive, maxIdle, idleTimeout int, wait bool) *redis.Pool
NewRedisPool creates a new pool. redisServer: redis server address. redisPassword: redis password. Leave it empty if there's no password. maxActive: Maximum number of connections allocated by the pool at a given time. When zero, there is no limit on the number of connections in the pool. maxIdle: Maximum number of idle connections in the pool. idleTimeout: Close connections after remaining idle for this duration(in second). If the value is zero, the idle connections are not closed. Applications should set the timeout to a value less than the server's timeout. wait: If Wait is true and the pool is at the MaxActive limit, then Get() waits for a connection to be returned to the pool before returning.
Example ¶
package main import ( "log" "sync/atomic" "github.com/northbright/redishelper" ) func main() { var ( success uint64 fail uint64 total uint64 maxActive = 1000 // try 10000(too many tcp connections.) maxIdle = 100 idleTimeout = 60 wait = false limitedConcurrency = 2000 // try 2000(>maxActive, pool exhausted.) concurrency = limitedConcurrency * 2 ) pool := redishelper.NewRedisPool(":6379", "", maxActive, maxIdle, idleTimeout, wait) defer pool.Close() sem := make(chan struct{}, limitedConcurrency) f := func(i int) { defer func() { <-sem }() atomic.AddUint64(&total, 1) conn := pool.Get() defer conn.Close() k := "pool_test" _, err := conn.Do("SET", k, i) if err != nil { atomic.AddUint64(&fail, 1) log.Printf("%v: SET error: %v", i, err) return } atomic.AddUint64(&success, 1) log.Printf("%v: SET ok", i) } for i := 0; i < concurrency; i++ { sem <- struct{}{} go f(i) } // After last goroutine is started, // there're still "concurrency" amount of goroutines running. // Make sure wait all goroutines to finish. for j := 0; j < cap(sem); j++ { sem <- struct{}{} log.Printf("----- j: %v", j) } totalFinal := atomic.LoadUint64(&total) successFinal := atomic.LoadUint64(&success) failFinal := atomic.LoadUint64(&fail) log.Printf("total: %v, success: %v, fail: %v", totalFinal, successFinal, failFinal) }
Output:
Types ¶
This section is empty.