2025-01-14 00:42:18 -08:00

77 lines
1.4 KiB
Go

package cache
import (
"context"
"fmt"
"net/url"
"strings"
"ultone/internal/tool"
"gitea.com/taozitaozi/gredis"
"github.com/go-redis/redis/v8"
)
func New(ctx context.Context, uri string) (Cache, error) {
var (
err error
newClient Cache
strs = strings.Split(uri, "::")
)
switch strs[0] {
case "memory":
gc := gredis.NewGredis(1024 * 1024)
newClient = &_mem{client: gc}
case "lru":
if newClient, err = newLRUCache(); err != nil {
return nil, err
}
case "redis":
var (
ins *url.URL
err error
)
if len(strs) != 2 {
return nil, fmt.Errorf("cache.Init: invalid cache uri: %s", uri)
}
uri := strs[1]
if !strings.Contains(uri, "://") {
uri = fmt.Sprintf("redis://%s", uri)
}
if ins, err = url.Parse(uri); err != nil {
return nil, fmt.Errorf("cache.Init: url parse cache uri: %s, err: %s", uri, err.Error())
}
addr := ins.Host
username := ins.User.Username()
password, _ := ins.User.Password()
var rc *redis.Client
rc = redis.NewClient(&redis.Options{
Addr: addr,
Username: username,
Password: password,
})
if err = rc.Ping(tool.Timeout(5)).Err(); err != nil {
return nil, fmt.Errorf("cache.Init: redis ping err: %s", err.Error())
}
newClient = &_redis{client: rc}
default:
return nil, fmt.Errorf("cache type %s not support", strs[0])
}
return newClient, nil
}
func Init(ctx context.Context, uri string) (err error) {
Client, err = New(ctx, uri)
return
}