github.com/wangyougui/gf/v2@v2.6.5/database/gredis/gredis.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 provides convenient client for redis server. 8 // 9 // Redis Client. 10 // 11 // Redis Commands Official: https://redis.io/commands 12 // 13 // Redis Chinese Documentation: http://redisdoc.com/ 14 package gredis 15 16 import ( 17 "github.com/wangyougui/gf/v2/errors/gcode" 18 "github.com/wangyougui/gf/v2/errors/gerror" 19 ) 20 21 // AdapterFunc is the function creating redis adapter. 22 type AdapterFunc func(config *Config) Adapter 23 24 var ( 25 // defaultAdapterFunc is the default adapter function creating redis adapter. 26 defaultAdapterFunc AdapterFunc = func(config *Config) Adapter { 27 return nil 28 } 29 ) 30 31 // New creates and returns a redis client. 32 // It creates a default redis adapter of go-redis. 33 func New(config ...*Config) (*Redis, error) { 34 var ( 35 usedConfig *Config 36 usedAdapter Adapter 37 ) 38 if len(config) > 0 && config[0] != nil { 39 // Redis client with go redis implements adapter from given configuration. 40 usedConfig = config[0] 41 usedAdapter = defaultAdapterFunc(config[0]) 42 } else if configFromGlobal, ok := GetConfig(); ok { 43 // Redis client with go redis implements adapter from package configuration. 44 usedConfig = configFromGlobal 45 usedAdapter = defaultAdapterFunc(configFromGlobal) 46 } 47 if usedConfig == nil { 48 return nil, gerror.NewCode( 49 gcode.CodeInvalidConfiguration, 50 `no configuration found for creating Redis client`, 51 ) 52 } 53 if usedAdapter == nil { 54 return nil, gerror.NewCode( 55 gcode.CodeNecessaryPackageNotImport, 56 errorNilAdapter, 57 ) 58 } 59 redis := &Redis{ 60 config: usedConfig, 61 localAdapter: usedAdapter, 62 } 63 return redis.initGroup(), nil 64 } 65 66 // NewWithAdapter creates and returns a redis client with given adapter. 67 func NewWithAdapter(adapter Adapter) (*Redis, error) { 68 if adapter == nil { 69 return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `adapter cannot be nil`) 70 } 71 redis := &Redis{localAdapter: adapter} 72 return redis.initGroup(), nil 73 } 74 75 // RegisterAdapterFunc registers default function creating redis adapter. 76 func RegisterAdapterFunc(adapterFunc AdapterFunc) { 77 defaultAdapterFunc = adapterFunc 78 }