github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/redis/redis.go (about)

     1  package redis
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"time"
     7  
     8  	"github.com/artisanhe/tools/conf"
     9  	"github.com/artisanhe/tools/conf/presets"
    10  	"github.com/artisanhe/tools/env"
    11  )
    12  
    13  type Redis struct {
    14  	Name           string
    15  	Protocol       string
    16  	Host           string           `conf:"env,upstream" validate:"@hostname"`
    17  	Port           int              `conf:"env"`
    18  	Password       presets.Password `conf:"env" validate:"@string(0,)"`
    19  	ConnectTimeout time.Duration
    20  	ReadTimeout    time.Duration
    21  	WriteTimeout   time.Duration
    22  	IdleTimeout    time.Duration
    23  	MaxActive      int
    24  	MaxIdle        int
    25  	Wait           bool
    26  	DB             string `conf:"env"`
    27  	cache          *RedisCache
    28  }
    29  
    30  func (r Redis) DockerDefaults() conf.DockerDefaults {
    31  	return conf.DockerDefaults{
    32  		"Host": "redis", //conf.RancherInternal("tool-deps", "redis"),
    33  		"Port": 36379,
    34  	}
    35  }
    36  
    37  func (r Redis) MarshalDefaults(v interface{}) {
    38  	if rd, ok := v.(*Redis); ok {
    39  		if rd.Name == "" {
    40  			rd.Name = os.Getenv("PROJECT_NAME")
    41  		}
    42  		if rd.Protocol == "" {
    43  			rd.Protocol = "tcp"
    44  		}
    45  		if rd.Port == 0 {
    46  			rd.Port = 6379
    47  		}
    48  		if rd.Password == "" {
    49  			//rd.Password = "redis"
    50  		}
    51  		if rd.ConnectTimeout == 0 {
    52  			rd.ConnectTimeout = 10 * time.Second
    53  		}
    54  		if rd.ReadTimeout == 0 {
    55  			rd.ReadTimeout = 10 * time.Second
    56  		}
    57  		if rd.WriteTimeout == 0 {
    58  			rd.WriteTimeout = 10 * time.Second
    59  		}
    60  		if rd.IdleTimeout == 0 {
    61  			rd.IdleTimeout = 240 * time.Second
    62  		}
    63  		if rd.MaxActive == 0 {
    64  			rd.MaxActive = 5
    65  		}
    66  		if rd.MaxIdle == 0 {
    67  			rd.MaxIdle = 3
    68  		}
    69  		if !rd.Wait {
    70  			rd.Wait = true
    71  		}
    72  		if rd.DB == "" {
    73  			rd.DB = "10"
    74  		}
    75  	}
    76  }
    77  
    78  func (r *Redis) Prefix(key string) string {
    79  	return fmt.Sprintf("%s::%s::%s", env.GetRuntimeEnv(), r.Name, key)
    80  }
    81  
    82  func (r *Redis) TopicFor(topic string, key string) string {
    83  	return r.Prefix(fmt.Sprintf("%s::%s", topic, key))
    84  }
    85  
    86  func (r *Redis) Init() {
    87  	if r.cache == nil {
    88  		r.cache = NewRedisCache()
    89  		err := r.cache.Start(r)
    90  		if err != nil {
    91  			panic(err)
    92  		}
    93  	}
    94  }
    95  
    96  func (r *Redis) GetCache() *RedisCache {
    97  	return r.cache
    98  }