1 Star 1 Fork 1

xiaoyutab / xgotool

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
init.go 2.99 KB
一键复制 编辑 原始数据 按行查看 历史
xiaoyutab 提交于 2024-05-16 15:52 . 添加xcache分组
// 缓存模块
package xcache
import (
"errors"
"fmt"
"sync"
"time"
"github.com/gomodule/redigo/redis"
)
// 因xgodb.Cachexxxxx使用稍微有些繁杂,所以此处将缓存模块进一步精简,并逐步废弃xgodb.Cachexxx操作
type Config struct {
Hosts string // Redis连接地址
Pass string // redis密码
RedisSelect uint8 // redis查询库
ErrFunc func(msg string, err error) // Redis报错记录函数,用于记录Redis的报错信息
// 以下的配置模块为程序内部使用的配置
Conn *redis.Pool // redis连接配置
CacheSync sync.Map // 程序内缓存定时
Connect redis.Conn // redis连接
DefaultTime time.Duration // 默认缓存时长
groupMaxLimit int // 分组内缓存最大数量,超过该数量后将会触发整个分组的清空操作
groupCounts int // 分组数量限制,即缓存中允许存在最多多少个分组
}
var _default Config = Config{
CacheSync: sync.Map{},
DefaultTime: time.Hour * 2,
groupMaxLimit: 100,
groupCounts: 100,
}
// 设置redis连接
//
// conf 缓存配置项
func Regedit(conf *Config) {
if conf == nil {
return
}
if conf.Hosts != "" {
_default.Hosts = conf.Hosts
}
if conf.DefaultTime > 0 {
_default.DefaultTime = conf.DefaultTime
}
if conf.RedisSelect > 0 {
_default.RedisSelect = conf.RedisSelect
}
if conf.Pass != "" {
_default.Pass = conf.Pass
}
if conf.ErrFunc != nil {
_default.ErrFunc = conf.ErrFunc
}
_default.Conn = &redis.Pool{
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", _default.Hosts)
},
}
}
// 移除缓存配置
func RemoveRegedit() {
_default.Hosts = ""
_default.Pass = ""
}
// 设置连接和密码,需要异步执行_default.Connect.Close()
func open() {
if _default.Connect == nil {
_default.Connect = _default.Conn.Get()
}
if _default.Pass != "" {
if _, err := _default.Connect.Do("AUTH", _default.Pass); err != nil {
errorFunc("缓存库密码认证报错", err)
_default.Connect = nil
}
}
if _default.Connect != nil && _default.RedisSelect != 0 {
if _, err := _default.Connect.Do("SELECT", _default.RedisSelect); err != nil {
errorFunc("缓存库认证失败", err)
_default.Connect = nil
}
}
}
// 执行redis关闭操作
func close() {
if _default.Connect == nil {
return
}
_default.Connect.Close()
_default.Connect = nil
}
// 错误返回
//
// msg 错误概述
// err 错误详情
func errorFunc(msg string, err error) error {
if _default.ErrFunc != nil {
_default.ErrFunc(msg, err)
}
return err
}
// 异常恢复函数
//
// msg 恢复描述关键词
func panic_recover(msg string) {
if r := recover(); r != nil {
_default.Connect = nil
switch err := r.(type) {
case string:
errorFunc("Panic "+msg+" 异常-1", errors.New(err))
case error:
errorFunc("Panic "+msg+" 异常-2", err)
default:
errorFunc("Panic "+msg+" 异常-3", fmt.Errorf("%T: %v", err, err))
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/xiaoyutab/xgotool.git
git@gitee.com:xiaoyutab/xgotool.git
xiaoyutab
xgotool
xgotool
v0.3.14

搜索帮助

344bd9b3 5694891 D2dac590 5694891