尝试写了一个demo,但是感觉不够灵活,有没有最佳实践可以参考一下?主要目的是解耦缓存逻辑与业务逻辑
```go
package cache
import "context"
//对缓存的个性化设置,如最大空间、过期时间等如何加入,处理缓存一致性、缓存穿透等问题?
type Cache interface {
Get(ctx context.Context, key string, ret interface{}) error
Set(ctx context.Context, key string, value interface{}) error
}
type RedisCache struct {
client int //假设是redis client
}
func (rc RedisCache) Get(ctx context.Context, key string, ret interface{}) error {
return nil
}
func (rc RedisCache) Set(ctx context.Context, key string, value interface{}) error {
return nil
}
type Service struct {
redis Cache
goCache Cache
mysql int
}
type mysqlGetFunc func(ctx context.Context, key string, ret interface{}) error
type Data1 struct {
}
//也可以做成一个接口
func (s *Service) GetDataFunc(ctx context.Context, mf mysqlGetFunc, key string, ret interface{}, caches ... Cache) error {
for _, c := range caches {
err := c.Get(ctx, key, &ret)
if err != nil {
return err
}
//if d exist -> return
}
err := mf(ctx, key, &ret)
if err != nil {
return err
}
for _, c := range caches {
//update cache
c.Set(ctx, key, ret)
}
return nil
}
func (s *Service) GetData1(ctx context.Context, key string, caches ... Cache) ([]*Data1, error){
ret := make([]*Data1, 0)
s.GetDataFunc(ctx, nil /*mysql.GetData1()*/, key, &ret, caches...)
return nil, nil
}
var _ Cache = (*RedisCache)(nil)
func test() {
service := &Service{redis: RedisCache{client: 1} }
service.GetData1(context.Background(), "key")
service.GetData1(context.Background(), "key", service.redis)
}
```
有疑问加站长微信联系(非本文作者)