85 lines
1.4 KiB
Go
85 lines
1.4 KiB
Go
package cache
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"loveuer/utodo/pkg/tool"
|
|
"net/url"
|
|
|
|
"github.com/dgraph-io/ristretto/v2"
|
|
"github.com/go-redis/redis/v8"
|
|
)
|
|
|
|
func New(opts ...Option) (Cache, error) {
|
|
var (
|
|
err error
|
|
cfg = &option{
|
|
ctx: context.Background(),
|
|
}
|
|
)
|
|
|
|
for _, opt := range opts {
|
|
opt(cfg)
|
|
}
|
|
|
|
if cfg.redis != nil {
|
|
var (
|
|
ins *url.URL
|
|
client *redis.Client
|
|
)
|
|
|
|
if ins, err = url.Parse(*cfg.redis); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
username := ins.User.Username()
|
|
password, _ := ins.User.Password()
|
|
|
|
client = redis.NewClient(&redis.Options{
|
|
Addr: ins.Host,
|
|
Username: username,
|
|
Password: password,
|
|
})
|
|
|
|
if err = client.Ping(tool.TimeoutCtx(cfg.ctx, 5)).Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return newRedis(cfg.ctx, client), nil
|
|
}
|
|
|
|
if cfg.memory {
|
|
var (
|
|
ins *ristretto.Cache[string, []byte]
|
|
)
|
|
|
|
if ins, err = ristretto.NewCache(&ristretto.Config[string, []byte]{
|
|
NumCounters: 1e7, // number of keys to track frequency of (10M).
|
|
MaxCost: 1 << 30, // maximum cost of cache (1GB).
|
|
BufferItems: 64, // number of keys per Get buffer.
|
|
}); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return newMemory(cfg.ctx, ins), nil
|
|
}
|
|
|
|
return nil, fmt.Errorf("invalid cache option")
|
|
}
|
|
|
|
func Init(opts ...Option) (err error) {
|
|
opt := &option{}
|
|
|
|
for _, optFn := range opts {
|
|
optFn(opt)
|
|
}
|
|
|
|
if opt.memory {
|
|
Default, err = New(opts...)
|
|
return err
|
|
}
|
|
|
|
Default, err = New(opts...)
|
|
return err
|
|
}
|