我正在使用 redigo 创建 PubSub,并且连接是由 redis 池创建的。
这是 Redis 池代码:
package main
import (
"os"
"os/signal"
"syscall"
"time"
"github.com/gomodule/redigo/redis"
)
type IRedis interface {
Addr() string
Conn() redis.Conn
Set(key string, body string) error
Close()
}
type Redis struct {
addr string
pool *redis.Pool
}
func NewRedis(addr string) *Redis {
r := &Redis{
addr,
&redis.Pool{
MaxIdle: 50000,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", addr)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
},
}
r.cleanupHook()
return r
}
func (r *Redis) cleanupHook() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)
signal.Notify(c, syscall.SIGKILL)
go func() {
<-c
r.pool.Close()
os.Exit(0)
}()
}
func (r *Redis) Addr() string {
return r.addr
}
func (r *Redis) Conn() redis.Conn {
return r.pool.Get()
}
func (r *Redis) Set(key string, body string) error {
p := r.pool.Get()
defer p.Close()
_, err := p.Do("SET", key, body)
return err
}
func (r *Redis) Close() {
r.pool.Close()
}
慕尼黑8549860
相关分类