123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package redis_client
- import (
- "context"
- "errors"
- "github.com/redis/go-redis/v9"
- "time"
- )
- type Client struct {
- redisClient *redis.Client
- }
- func NewClient(address string, userName string, password string, db int) (*Client, error) {
- if address == "" {
- return nil, errors.New("redis address不能为空")
- }
- return &Client{redisClient: redis.NewClient(&redis.Options{
- Addr: address,
- Username: userName,
- Password: password,
- DB: db,
- })}, nil
- }
- func Destroy(client *Client) error {
- if client == nil || client.redisClient == nil {
- return nil
- }
- err := client.redisClient.Close()
- if err != nil {
- return err
- }
- client.redisClient = nil
- return nil
- }
- func (client *Client) Set(key string, value any, expireSec int64) error {
- cmd := client.redisClient.Set(context.Background(), key, value, time.Second*time.Duration(expireSec))
- if cmd.Err() != nil {
- return cmd.Err()
- }
- return nil
- }
- func (client *Client) Get(key string) (any, error) {
- cmd := client.redisClient.Get(context.Background(), key)
- if cmd.Err() != nil {
- if cmd.Err().Error() == redis.Nil.Error() {
- return nil, nil
- }
- return nil, cmd.Err()
- }
- return cmd.Val(), nil
- }
- func (client *Client) GetMulti(keys []string) (map[string]any, error) {
- result := make(map[string]any)
- for _, key := range keys {
- cmd := client.redisClient.Get(context.Background(), key)
- if cmd.Err() != nil {
- if cmd.Err().Error() == redis.Nil.Error() {
- result[key] = nil
- continue
- }
- return nil, cmd.Err()
- }
- result[key] = cmd.Val()
- }
- return result, nil
- }
|