package data import ( "context" "ky-go-kratos/internal/conf" "time" "github.com/go-kratos/kratos/v2/log" "github.com/redis/go-redis/v9" ) type Redis struct { rdb *redis.Client } func NewRedis(c *conf.Data, db int) *redis.Client { opt, err := redis.ParseURL(c.Redis.Source) if err != nil { panic(err) } opt.DB = db rdb := redis.NewClient(opt) timeout, cancelFunc := context.WithTimeout(context.Background(), time.Second*2) defer cancelFunc() err = rdb.Ping(timeout).Err() if err != nil { log.Fatalf("redis connect error: %v", err) } log.Info("redis", "connected to redis", c.Redis.Source) return rdb } func (r *Redis) Get(ctx context.Context, key string) (string, error) { return r.rdb.Get(ctx, key).Result() } func (r *Redis) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error { return r.rdb.Set(ctx, key, value, expiration).Err() } func (r *Redis) Del(ctx context.Context, key string) error { return r.rdb.Del(ctx, key).Err() } func (r *Redis) Close() error { return r.rdb.Close() }