github.com/openimsdk/tools@v0.0.49/db/redisutil/redis.go (about)

     1  // Copyright © 2023 OpenIM. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package redisutil
    16  
    17  import (
    18  	"context"
    19  
    20  	"github.com/openimsdk/tools/errs"
    21  	"github.com/redis/go-redis/v9"
    22  )
    23  
    24  // Config defines the configuration parameters for a Redis client, including
    25  // options for both single-node and cluster mode connections.
    26  type Config struct {
    27  	ClusterMode bool     // Whether to use Redis in cluster mode.
    28  	Address     []string // List of Redis server addresses (host:port).
    29  	Username    string   // Username for Redis authentication (Redis 6 ACL).
    30  	Password    string   // Password for Redis authentication.
    31  	MaxRetry    int      // Maximum number of retries for a command.
    32  	DB          int      // Database number to connect to, for non-cluster mode.
    33  	PoolSize    int      // Number of connections to pool.
    34  }
    35  
    36  func NewRedisClient(ctx context.Context, config *Config) (redis.UniversalClient, error) {
    37  	if len(config.Address) == 0 {
    38  		return nil, errs.New("redis address is empty").Wrap()
    39  	}
    40  	var cli redis.UniversalClient
    41  	if config.ClusterMode || len(config.Address) > 1 {
    42  		opt := &redis.ClusterOptions{
    43  			Addrs:      config.Address,
    44  			Username:   config.Username,
    45  			Password:   config.Password,
    46  			PoolSize:   config.PoolSize,
    47  			MaxRetries: config.MaxRetry,
    48  		}
    49  		cli = redis.NewClusterClient(opt)
    50  	} else {
    51  		opt := &redis.Options{
    52  			Addr:       config.Address[0],
    53  			Username:   config.Username,
    54  			Password:   config.Password,
    55  			DB:         config.DB,
    56  			PoolSize:   config.PoolSize,
    57  			MaxRetries: config.MaxRetry,
    58  		}
    59  		cli = redis.NewClient(opt)
    60  	}
    61  	if err := cli.Ping(ctx).Err(); err != nil {
    62  		return nil, errs.WrapMsg(err, "Redis Ping failed", "Address", config.Address, "Username", config.Username, "ClusterMode", config.ClusterMode)
    63  	}
    64  	return cli, nil
    65  }