uauth/pkg/cache/init.go

75 lines
1.4 KiB
Go
Raw Normal View History

2024-10-23 17:46:15 +08:00
package cache
import (
"fmt"
"gitea.com/loveuer/gredis"
2024-10-23 17:46:15 +08:00
"github.com/go-redis/redis/v8"
"net/url"
"strings"
"uauth/tool"
2024-10-23 17:46:15 +08:00
)
func Init(uri string) (err error) {
Client, err = New(uri)
return err
}
2024-10-23 17:46:15 +08:00
func New(uri string) (Cache, error) {
2024-10-23 17:46:15 +08:00
var (
client Cache
err error
2024-10-23 17:46:15 +08:00
)
strs := strings.Split(uri, "::")
switch strs[0] {
case "memory":
gc := gredis.NewGredis(1024 * 1024)
client = &_mem{client: gc}
2024-10-23 17:46:15 +08:00
case "lru":
if client, err = newLRUCache(); err != nil {
return nil, err
2024-10-23 17:46:15 +08:00
}
case "redis":
var (
ins *url.URL
err error
)
if len(strs) != 2 {
return nil, fmt.Errorf("cache.Init: invalid cache uri: %s", uri)
2024-10-23 17:46:15 +08:00
}
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())
2024-10-23 17:46:15 +08:00
}
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())
2024-10-23 17:46:15 +08:00
}
client = &_redis{client: rc}
2024-10-23 17:46:15 +08:00
default:
return nil, fmt.Errorf("cache type %s not support", strs[0])
2024-10-23 17:46:15 +08:00
}
return client, nil
2024-10-23 17:46:15 +08:00
}