1 Star 2 Fork 3

kristas/booting-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
redis_cache.go 2.83 KB
一键复制 编辑 原始数据 按行查看 历史
kristas 提交于 2021-04-23 18:42 . feat: add auto configure
package redis_cache_impl
import (
"context"
"gitee.com/kristas/booting-go/framework/cache"
"gitee.com/kristas/booting-go/framework/core/bean"
"gitee.com/kristas/booting-go/framework/core/configure"
"gitee.com/kristas/booting-go/framework/logging"
"github.com/go-redis/redis/v8"
"time"
)
func init() {
cache.Register("redis", new(RedisCache))
}
type RedisCache struct {
bean.Component
client *redis.Client
log logging.Logger
ctx context.Context
}
func (r *RedisCache) Conn() (cache cache.ICache, err error) {
log := logging.GetLog()
r.ctx = context.Background()
var config = new(Configure)
configure.InjectConfiguration(config)
r.client = redis.NewClient(config.Adapter())
result, err := r.client.Ping(context.Background()).Result()
if err != nil {
return
}
log.Infof("ping redis: %s", result)
cache = r
return
}
func (r *RedisCache) Set(key string, value interface{}) (string, error) {
return r.client.Set(r.ctx, key, value, 0).Result()
}
func (r *RedisCache) Del(key string) (int64, error) {
return r.client.Del(r.ctx, key).Result()
}
func (r *RedisCache) Get(key string) (string, error) {
return r.client.Get(r.ctx, key).Result()
}
type Configure struct {
Network string `yaml:"network"`
Host string `yaml:"host"`
Username string `yaml:"username"`
Password string `yaml:"password"`
DB int `yaml:"db"`
MaxRetries int `yaml:"max_retries"`
MinRetryBackoff time.Duration `yaml:"min_retry_backoff"`
MaxRetryBackoff time.Duration `yaml:"max_retry_backoff"`
DialTimeout time.Duration `yaml:"dial_timeout"`
ReadTimeout time.Duration `yaml:"read_timeout"`
WriteTimeout time.Duration `yaml:"write_timeout"`
PoolSize int `yaml:"pool_size"`
MinIdleConns int `yaml:"min_idle_conns"`
MaxConnAge time.Duration `yaml:"max_conn_age"`
PoolTimeout time.Duration `yaml:"pool_timeout"`
IdleTimeout time.Duration `yaml:"idle_timeout"`
IdleCheckFrequency time.Duration `yaml:"idle_check_frequency"`
}
func (r *Configure) Prefix() string {
return "application.redis"
}
func (r *Configure) Adapter() *redis.Options {
return &redis.Options{
Network: r.Network,
Addr: r.Host,
Username: r.Username,
Password: r.Password,
DB: r.DB,
MaxRetries: r.MaxRetries,
MinRetryBackoff: r.MinRetryBackoff,
MaxRetryBackoff: r.MaxRetryBackoff,
DialTimeout: r.DialTimeout,
ReadTimeout: r.ReadTimeout,
WriteTimeout: r.WriteTimeout,
PoolSize: r.PoolSize,
MinIdleConns: r.MinIdleConns,
MaxConnAge: r.MaxConnAge,
PoolTimeout: r.PoolTimeout,
IdleTimeout: r.IdleTimeout,
IdleCheckFrequency: r.IdleCheckFrequency,
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/kristas/booting-go.git
git@gitee.com:kristas/booting-go.git
kristas
booting-go
booting-go
v1.2.6

搜索帮助