git.zd.zone/hrpc/hrpc@v0.0.12/database/redis/redis.go (about)

     1  package redis
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  
     7  	"git.zd.zone/hrpc/hrpc/database"
     8  	redisv8 "github.com/go-redis/redis/v8"
     9  )
    10  
    11  type Redis struct {
    12  	conn    *redisv8.Client
    13  	options Options
    14  }
    15  
    16  var r *Redis
    17  
    18  var (
    19  	// ErrNil when key does not exist.
    20  	ErrNil = redisv8.Nil
    21  )
    22  
    23  // Client returns the handler to operate redis if success
    24  func Client() *redisv8.Client {
    25  	return r.conn
    26  }
    27  
    28  func (r *Redis) Load(src []byte) error {
    29  	// If the value of customized is true (enabled),
    30  	// which means DOES NOT use the configurations from the configuration center.
    31  	if r.options.customized {
    32  		return nil
    33  	}
    34  	if err := json.Unmarshal(src, &r.options); err != nil {
    35  		return err
    36  	}
    37  	return nil
    38  }
    39  
    40  func (r Redis) dataSource() *redisv8.Options {
    41  	cfg := &redisv8.Options{
    42  		Network:    "tcp",
    43  		Addr:       fmt.Sprintf("%s:%d", r.options.Address, r.options.Port),
    44  		Username:   r.options.Username,
    45  		Password:   r.options.Password,
    46  		DB:         r.options.DB,
    47  		MaxRetries: r.options.MaxRetries,
    48  	}
    49  	return cfg
    50  }
    51  
    52  func (r *Redis) Connect() error {
    53  	r.Destory()
    54  
    55  	r.conn = redisv8.NewClient(r.dataSource())
    56  	pong, err := r.conn.Ping(r.conn.Context()).Result()
    57  	if err != nil || pong != "PONG" {
    58  		return err
    59  	}
    60  	return nil
    61  }
    62  
    63  // Valid returns a bool valud to determine whether the connection is ready to use
    64  func Valid() bool {
    65  	if r == nil {
    66  		return false
    67  	}
    68  	if r.conn == nil {
    69  		return false
    70  	}
    71  	pong, err := r.conn.Ping(r.conn.Context()).Result()
    72  	if err != nil || pong != "PONG" {
    73  		return false
    74  	}
    75  	return true
    76  }
    77  
    78  func (r Redis) Name() string {
    79  	return "redis"
    80  }
    81  
    82  func (r *Redis) Destory() {
    83  	if r.conn != nil {
    84  		r.conn.Close()
    85  	}
    86  }
    87  
    88  func New(opts ...Option) *Redis {
    89  	var options = Options{
    90  		Port:       6379,
    91  		DB:         0,
    92  		MaxRetries: 3,
    93  		customized: false,
    94  	}
    95  	for _, o := range opts {
    96  		o(&options)
    97  	}
    98  
    99  	if r != nil {
   100  		r.Destory()
   101  	}
   102  	r = &Redis{
   103  		options: options,
   104  	}
   105  	return r
   106  }
   107  
   108  var _ database.Database = (*Redis)(nil)