feat: add memory cache
This commit is contained in:
42
database/cache/new.go
vendored
42
database/cache/new.go
vendored
@ -4,35 +4,31 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"gitea.loveuer.com/yizhisec/packages/tool"
|
||||
"github.com/dgraph-io/ristretto/v2"
|
||||
"github.com/go-redis/redis/v8"
|
||||
_ "github.com/go-redis/redis/v8"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
var (
|
||||
defaultRedis = "redis://127.0.0.1:6379"
|
||||
)
|
||||
|
||||
func New(opts ...OptionFn) (Cache, error) {
|
||||
func New(opts ...Option) (Cache, error) {
|
||||
var (
|
||||
err error
|
||||
cfg = &config{
|
||||
ctx: context.Background(),
|
||||
redis: &defaultRedis,
|
||||
opt = &option{
|
||||
ctx: context.Background(),
|
||||
}
|
||||
)
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(cfg)
|
||||
for _, fn := range opts {
|
||||
fn(opt)
|
||||
}
|
||||
|
||||
if cfg.redis != nil {
|
||||
if opt.redis != nil {
|
||||
var (
|
||||
ins *url.URL
|
||||
client *redis.Client
|
||||
)
|
||||
|
||||
if ins, err = url.Parse(*cfg.redis); err != nil {
|
||||
if ins, err = url.Parse(*opt.redis); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@ -45,17 +41,33 @@ func New(opts ...OptionFn) (Cache, error) {
|
||||
Password: password,
|
||||
})
|
||||
|
||||
if err = client.Ping(tool.TimeoutCtx(cfg.ctx, 5)).Err(); err != nil {
|
||||
if err = client.Ping(tool.TimeoutCtx(opt.ctx, 5)).Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newRedis(cfg.ctx, client), nil
|
||||
return newRedis(opt.ctx, client), nil
|
||||
}
|
||||
|
||||
if opt.memory {
|
||||
var (
|
||||
ins *ristretto.Cache[string, []byte]
|
||||
)
|
||||
|
||||
if ins, err = ristretto.NewCache(&ristretto.Config[string, []byte]{
|
||||
NumCounters: 1e7,
|
||||
MaxCost: 1 << 30,
|
||||
BufferItems: 64,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newMemory(opt.ctx, ins), nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("invalid cache config")
|
||||
}
|
||||
|
||||
func Init(opts ...OptionFn) (err error) {
|
||||
func Init(opts ...Option) (err error) {
|
||||
Default, err = New(opts...)
|
||||
return err
|
||||
}
|
||||
|
Reference in New Issue
Block a user