74 lines
1.2 KiB
Go
74 lines
1.2 KiB
Go
package cache
|
|
|
|
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"
|
|
)
|
|
|
|
func New(opts ...Option) (Cache, error) {
|
|
var (
|
|
err error
|
|
opt = &option{
|
|
ctx: context.Background(),
|
|
}
|
|
)
|
|
|
|
for _, fn := range opts {
|
|
fn(opt)
|
|
}
|
|
|
|
if opt.redis != nil {
|
|
var (
|
|
ins *url.URL
|
|
client *redis.Client
|
|
)
|
|
|
|
if ins, err = url.Parse(*opt.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(opt.ctx, 5)).Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
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 ...Option) (err error) {
|
|
Default, err = New(opts...)
|
|
return err
|
|
}
|