github.com/wangyougui/gf/v2@v2.6.5/database/gredis/gredis_config.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package gredis
     8  
     9  import (
    10  	"context"
    11  	"crypto/tls"
    12  	"time"
    13  
    14  	"github.com/wangyougui/gf/v2/container/gmap"
    15  	"github.com/wangyougui/gf/v2/errors/gcode"
    16  	"github.com/wangyougui/gf/v2/errors/gerror"
    17  	"github.com/wangyougui/gf/v2/internal/intlog"
    18  	"github.com/wangyougui/gf/v2/util/gconv"
    19  )
    20  
    21  // Config is redis configuration.
    22  type Config struct {
    23  	// Address It supports single and cluster redis server. Multiple addresses joined with char ','. Eg: 192.168.1.1:6379, 192.168.1.2:6379.
    24  	Address         string        `json:"address"`
    25  	Db              int           `json:"db"`              // Redis db.
    26  	User            string        `json:"user"`            // Username for AUTH.
    27  	Pass            string        `json:"pass"`            // Password for AUTH.
    28  	SentinelUser    string        `json:"sentinel_user"`   // Username for sentinel AUTH.
    29  	SentinelPass    string        `json:"sentinel_pass"`   // Password for sentinel AUTH.
    30  	MinIdle         int           `json:"minIdle"`         // Minimum number of connections allowed to be idle (default is 0)
    31  	MaxIdle         int           `json:"maxIdle"`         // Maximum number of connections allowed to be idle (default is 10)
    32  	MaxActive       int           `json:"maxActive"`       // Maximum number of connections limit (default is 0 means no limit).
    33  	MaxConnLifetime time.Duration `json:"maxConnLifetime"` // Maximum lifetime of the connection (default is 30 seconds, not allowed to be set to 0)
    34  	IdleTimeout     time.Duration `json:"idleTimeout"`     // Maximum idle time for connection (default is 10 seconds, not allowed to be set to 0)
    35  	WaitTimeout     time.Duration `json:"waitTimeout"`     // Timed out duration waiting to get a connection from the connection pool.
    36  	DialTimeout     time.Duration `json:"dialTimeout"`     // Dial connection timeout for TCP.
    37  	ReadTimeout     time.Duration `json:"readTimeout"`     // Read timeout for TCP. DO NOT set it if not necessary.
    38  	WriteTimeout    time.Duration `json:"writeTimeout"`    // Write timeout for TCP.
    39  	MasterName      string        `json:"masterName"`      // Used in Redis Sentinel mode.
    40  	TLS             bool          `json:"tls"`             // Specifies whether TLS should be used when connecting to the server.
    41  	TLSSkipVerify   bool          `json:"tlsSkipVerify"`   // Disables server name verification when connecting over TLS.
    42  	TLSConfig       *tls.Config   `json:"-"`               // TLS Config to use. When set TLS will be negotiated.
    43  	SlaveOnly       bool          `json:"slaveOnly"`       // Route all commands to slave read-only nodes.
    44  	Cluster         bool          `json:"cluster"`         // Specifies whether cluster mode be used.
    45  	Protocol        int           `json:"protocol"`        // Specifies the RESP version (Protocol 2 or 3.)
    46  }
    47  
    48  const (
    49  	DefaultGroupName = "default" // Default configuration group name.
    50  )
    51  
    52  var (
    53  	// Configuration groups.
    54  	localConfigMap = gmap.NewStrAnyMap(true)
    55  )
    56  
    57  // SetConfig sets the global configuration for specified group.
    58  // If `name` is not passed, it sets configuration for the default group name.
    59  func SetConfig(config *Config, name ...string) {
    60  	group := DefaultGroupName
    61  	if len(name) > 0 {
    62  		group = name[0]
    63  	}
    64  	localConfigMap.Set(group, config)
    65  
    66  	intlog.Printf(context.TODO(), `SetConfig for group "%s": %+v`, group, config)
    67  }
    68  
    69  // SetConfigByMap sets the global configuration for specified group with map.
    70  // If `name` is not passed, it sets configuration for the default group name.
    71  func SetConfigByMap(m map[string]interface{}, name ...string) error {
    72  	group := DefaultGroupName
    73  	if len(name) > 0 {
    74  		group = name[0]
    75  	}
    76  	config, err := ConfigFromMap(m)
    77  	if err != nil {
    78  		return err
    79  	}
    80  	localConfigMap.Set(group, config)
    81  	return nil
    82  }
    83  
    84  // ConfigFromMap parses and returns config from given map.
    85  func ConfigFromMap(m map[string]interface{}) (config *Config, err error) {
    86  	config = &Config{}
    87  	if err = gconv.Scan(m, config); err != nil {
    88  		err = gerror.NewCodef(gcode.CodeInvalidConfiguration, `invalid redis configuration: %#v`, m)
    89  	}
    90  	if config.DialTimeout < time.Second {
    91  		config.DialTimeout = config.DialTimeout * time.Second
    92  	}
    93  	if config.WaitTimeout < time.Second {
    94  		config.WaitTimeout = config.WaitTimeout * time.Second
    95  	}
    96  	if config.WriteTimeout < time.Second {
    97  		config.WriteTimeout = config.WriteTimeout * time.Second
    98  	}
    99  	if config.ReadTimeout < time.Second {
   100  		config.ReadTimeout = config.ReadTimeout * time.Second
   101  	}
   102  	if config.IdleTimeout < time.Second {
   103  		config.IdleTimeout = config.IdleTimeout * time.Second
   104  	}
   105  	if config.MaxConnLifetime < time.Second {
   106  		config.MaxConnLifetime = config.MaxConnLifetime * time.Second
   107  	}
   108  	if config.Protocol != 2 && config.Protocol != 3 {
   109  		config.Protocol = 3
   110  	}
   111  	return
   112  }
   113  
   114  // GetConfig returns the global configuration with specified group name.
   115  // If `name` is not passed, it returns configuration of the default group name.
   116  func GetConfig(name ...string) (config *Config, ok bool) {
   117  	group := DefaultGroupName
   118  	if len(name) > 0 {
   119  		group = name[0]
   120  	}
   121  	if v := localConfigMap.Get(group); v != nil {
   122  		return v.(*Config), true
   123  	}
   124  	return &Config{}, false
   125  }
   126  
   127  // RemoveConfig removes the global configuration with specified group.
   128  // If `name` is not passed, it removes configuration of the default group name.
   129  func RemoveConfig(name ...string) {
   130  	group := DefaultGroupName
   131  	if len(name) > 0 {
   132  		group = name[0]
   133  	}
   134  	localConfigMap.Remove(group)
   135  
   136  	intlog.Printf(context.TODO(), `RemoveConfig: %s`, group)
   137  }
   138  
   139  // ClearConfig removes all configurations of redis.
   140  func ClearConfig() {
   141  	localConfigMap.Clear()
   142  }