-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: implement Redis cache client (#20)
- Loading branch information
1 parent
e33d5c8
commit 954e93e
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package redis | ||
|
||
import ( | ||
"context" | ||
"time" | ||
|
||
ozzo "github.com/go-ozzo/ozzo-validation/v4" | ||
"github.com/redis/go-redis/v9" | ||
) | ||
|
||
// Cache is a Redis cache | ||
type Cache struct { | ||
client *redis.Client | ||
options *Options | ||
} | ||
|
||
type Options struct { | ||
Address string | ||
ConnectionTimeout time.Duration | ||
} | ||
|
||
func (o Options) Validate() error { | ||
return ozzo.ValidateStruct(&o, | ||
ozzo.Field(&o.Address, ozzo.Required), | ||
ozzo.Field(&o.ConnectionTimeout, ozzo.Required, ozzo.Min(1*time.Second)), | ||
) | ||
} | ||
|
||
// NewCache creates a new Cache | ||
func NewCache(options *Options) (*Cache, error) { | ||
if err := options.Validate(); err != nil { | ||
return nil, err | ||
} | ||
|
||
client := redis.NewClient(&redis.Options{ | ||
Addr: options.Address, | ||
}) | ||
|
||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
defer cancel() | ||
|
||
if err := client.Ping(ctx).Err(); err != nil { | ||
return nil, err | ||
} | ||
|
||
return &Cache{ | ||
client: client, | ||
options: options, | ||
}, nil | ||
} |