| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package utils
- import (
- "context"
- "log"
- "strconv"
- "time"
- beego "github.com/beego/beego/v2/server/web"
- "github.com/go-redis/redis/v8"
- )
- var RedisClient *redis.Client
- func redisString(key string, fallback string) string {
- v, err := beego.AppConfig.String(key)
- if err != nil || v == "" {
- return fallback
- }
- return v
- }
- func redisInt(key string, fallback int) int {
- raw, err := beego.AppConfig.String(key)
- if err != nil || raw == "" {
- return fallback
- }
- v, err := strconv.Atoi(raw)
- if err != nil || v < 0 {
- log.Printf("invalid redis config %s=%q, fallback=%d", key, raw, fallback)
- return fallback
- }
- return v
- }
- func redisBool(key string, fallback bool) bool {
- raw, err := beego.AppConfig.String(key)
- if err != nil || raw == "" {
- return fallback
- }
- v, err := strconv.ParseBool(raw)
- if err != nil {
- log.Printf("invalid redis config %s=%q, fallback=%t", key, raw, fallback)
- return fallback
- }
- return v
- }
- func InitRedis() error {
- if !redisBool("redis_enable", false) {
- return nil
- }
- addr := redisString("redis_addr", "127.0.0.1:6379")
- password := redisString("redis_password", "")
- db := redisInt("redis_db", 0)
- poolSize := redisInt("redis_pool_size", 10)
- minIdleConns := redisInt("redis_min_idle_conns", 2)
- dialTimeoutMS := redisInt("redis_dial_timeout_ms", 5000)
- readTimeoutMS := redisInt("redis_read_timeout_ms", 3000)
- writeTimeoutMS := redisInt("redis_write_timeout_ms", 3000)
- pingTimeoutMS := redisInt("redis_ping_timeout_ms", 3000)
- client := redis.NewClient(&redis.Options{
- Addr: addr,
- Password: password,
- DB: db,
- PoolSize: poolSize,
- MinIdleConns: minIdleConns,
- DialTimeout: time.Duration(dialTimeoutMS) * time.Millisecond,
- ReadTimeout: time.Duration(readTimeoutMS) * time.Millisecond,
- WriteTimeout: time.Duration(writeTimeoutMS) * time.Millisecond,
- })
- ctx, cancel := context.WithTimeout(context.Background(), time.Duration(pingTimeoutMS)*time.Millisecond)
- defer cancel()
- if err := client.Ping(ctx).Err(); err != nil {
- _ = client.Close()
- return err
- }
- RedisClient = client
- log.Printf("redis connected: addr=%s db=%d", addr, db)
- return nil
- }
- func CloseRedis() {
- if RedisClient == nil {
- return
- }
- _ = RedisClient.Close()
- }
|