|
| 1 | +package ecache |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/pkg/errors" |
| 10 | + "golang.org/x/exp/constraints" |
| 11 | + "golang.org/x/sync/singleflight" |
| 12 | +) |
| 13 | + |
| 14 | +var ( |
| 15 | + singleFlightGroup singleflight.Group |
| 16 | + |
| 17 | + // Marshal 默认序列化方案 |
| 18 | + Marshal func(v any) ([]byte, error) = json.Marshal |
| 19 | + // Unmarshal 默认反序列化方案 |
| 20 | + Unmarshal func(data []byte, v any) error = json.Unmarshal |
| 21 | + // Expiration 缓存默认过期时间 |
| 22 | + Expiration time.Duration |
| 23 | + // Disabled 缓存开关 |
| 24 | + Disabled bool |
| 25 | + // 缓存键名分隔符 |
| 26 | + Delimiter = ':' |
| 27 | +) |
| 28 | + |
| 29 | +type Cache interface { |
| 30 | + Del(ctx context.Context, keys ...string) (affected int64, err error) |
| 31 | + Get(ctx context.Context, key string) (val []byte, err error) |
| 32 | + GetAsUint64(ctx context.Context, key string) (val uint64, err error) |
| 33 | + Set(ctx context.Context, key string, val []byte, expire time.Duration) error |
| 34 | + IsKeyNotFound(err error) bool |
| 35 | +} |
| 36 | + |
| 37 | +type CacheableEntity[INT constraints.Integer] interface { |
| 38 | + ID() INT |
| 39 | +} |
| 40 | + |
| 41 | +// DelCachedEntity 删除指定键的缓存数据 |
| 42 | +func DelCachedEntity(ctx context.Context, cache Cache, key string) (affected int64, err error) { |
| 43 | + if Disabled { |
| 44 | + return 0, nil |
| 45 | + } |
| 46 | + |
| 47 | + if affected, err = cache.Del(ctx, key); err != nil { |
| 48 | + return affected, errors.WithStack(err) |
| 49 | + } |
| 50 | + return affected, nil |
| 51 | +} |
| 52 | + |
| 53 | +// GetEntityByID 返回主键ID对应的实体对象。 |
| 54 | +// 查找顺序:主键ID --> 缓存中实体对象 --> 数据库中实体对象。 |
| 55 | +// 局限: |
| 56 | +// 1、缓存 key格式无法自定义且不够内聚 |
| 57 | +func GetEntityByID[T CacheableEntity[INT], INT constraints.Integer]( |
| 58 | + ctx context.Context, |
| 59 | + cache Cache, |
| 60 | + entityKeyPrefix string, |
| 61 | + id INT, |
| 62 | + getEntityByID func(context.Context, INT) (*T, error), |
| 63 | +) (*T, error) { |
| 64 | + // 0、若未启用缓存,则直接查询数据库。 |
| 65 | + if Disabled { |
| 66 | + one, err := getEntityByID(ctx, id) |
| 67 | + if err != nil { |
| 68 | + return nil, errors.WithStack(err) |
| 69 | + } |
| 70 | + return one, nil |
| 71 | + } |
| 72 | + |
| 73 | + // 1、优先尝试从缓存中获取对象 |
| 74 | + key := fmt.Sprintf("%s%c%d", entityKeyPrefix, Delimiter, id) |
| 75 | + |
| 76 | + data, err := cache.Get(ctx, key) |
| 77 | + if err != nil && !cache.IsKeyNotFound(err) { |
| 78 | + return nil, errors.WithStack(err) |
| 79 | + } |
| 80 | + |
| 81 | + if err == nil { |
| 82 | + // 2、若获取到键对应的值,尝试反序列化,并返回对象。 |
| 83 | + var one T |
| 84 | + if err = Unmarshal(data, &one); err == nil { |
| 85 | + return &one, nil |
| 86 | + } |
| 87 | + // 若反序列化失败,不返回,允许继续向下执行。 |
| 88 | + } |
| 89 | + |
| 90 | + // 2、从数据库查询指定ID对象 |
| 91 | + entity, err, _ := singleFlightGroup.Do(key, func() (any, error) { // 防止缓存击穿 |
| 92 | + return getEntityByID(ctx, id) |
| 93 | + }) |
| 94 | + if err != nil { |
| 95 | + return nil, errors.WithStack(err) |
| 96 | + } |
| 97 | + |
| 98 | + // 3、序列化对象并存入Redis |
| 99 | + if data, err = Marshal(entity); err != nil { |
| 100 | + return nil, errors.WithStack(err) |
| 101 | + } |
| 102 | + if err = cache.Set(ctx, key, data, Expiration); err != nil { |
| 103 | + return nil, errors.WithStack(err) |
| 104 | + } |
| 105 | + |
| 106 | + // 4、返回查询到的对象 |
| 107 | + return entity.(*T), nil |
| 108 | +} |
| 109 | + |
| 110 | +// GetEntitiesByID 从Redis缓存中读取指定实体列表。若缓存中不存在,则从指定方法中读取并存入Redis缓存。 |
| 111 | +func GetEntitiesByID[T CacheableEntity[INT], INT constraints.Integer]( |
| 112 | + ctx context.Context, |
| 113 | + cache Cache, |
| 114 | + entityKeyPrefix string, |
| 115 | + id INT, |
| 116 | + getEntitiesByID func(context.Context, INT) ([]*T, error), |
| 117 | +) ([]*T, error) { |
| 118 | + var err error |
| 119 | + var items []*T |
| 120 | + |
| 121 | + // 0、若未启用缓存,则直接查询数据库。 |
| 122 | + if Disabled { |
| 123 | + if items, err = getEntitiesByID(ctx, id); err != nil { |
| 124 | + return nil, errors.WithStack(err) |
| 125 | + } |
| 126 | + return items, nil |
| 127 | + } |
| 128 | + |
| 129 | + // 1、优先尝试从Redis中获取对象列表 |
| 130 | + key := fmt.Sprintf("%s%citems%c%d", entityKeyPrefix, Delimiter, Delimiter, id) |
| 131 | + |
| 132 | + data, err := cache.Get(ctx, key) |
| 133 | + if err != nil && !cache.IsKeyNotFound(err) { |
| 134 | + return nil, errors.WithStack(err) |
| 135 | + } |
| 136 | + |
| 137 | + if err == nil { |
| 138 | + // 2、若获取到键对应的值,尝试反序列化,并返回对象列表。 |
| 139 | + if err = Unmarshal(data, &items); err == nil { |
| 140 | + return items, nil |
| 141 | + } |
| 142 | + // 若反序列化失败,不返回,允许继续向下执行。 |
| 143 | + } |
| 144 | + |
| 145 | + // 2、从数据库查询指定ID对象列表 |
| 146 | + entities, err, _ := singleFlightGroup.Do(key, func() (any, error) { |
| 147 | + return getEntitiesByID(ctx, id) |
| 148 | + }) |
| 149 | + if err != nil { |
| 150 | + return nil, err |
| 151 | + } |
| 152 | + |
| 153 | + items = entities.([]*T) |
| 154 | + if len(items) == 0 { |
| 155 | + return items, nil |
| 156 | + } |
| 157 | + |
| 158 | + // 3、序列化对象列表并存入Redis |
| 159 | + if data, err = Marshal(&items); err != nil { |
| 160 | + return nil, errors.WithStack(err) |
| 161 | + } |
| 162 | + if err = cache.Set(ctx, key, data, Expiration); err != nil { |
| 163 | + return nil, errors.WithStack(err) |
| 164 | + } |
| 165 | + |
| 166 | + return items, nil |
| 167 | +} |
| 168 | + |
| 169 | +// UniqueKey 唯一索引约束 |
| 170 | +type UniqueKey interface { |
| 171 | + ~string | constraints.Integer |
| 172 | +} |
| 173 | + |
| 174 | +// GetEntityByUniqueKey 返回唯一索引值对应的实体对象。 |
| 175 | +// 查找顺序:唯一索引值 --> Redis中主键ID --> 数据库中主键ID --> Redis中实体对象 --> 数据库中实体对象。 |
| 176 | +// 局限: |
| 177 | +// 1、Redis key格式无法自定义 |
| 178 | +// 2、不支持联合唯一索引 |
| 179 | +// 3、多一次查询 |
| 180 | +func GetEntityByUniqueKey[T CacheableEntity[INT], INT constraints.Integer, UK UniqueKey]( |
| 181 | + ctx context.Context, |
| 182 | + cache Cache, |
| 183 | + entityKeyPrefix string, |
| 184 | + ukKeyPrefix string, |
| 185 | + ukVal UK, |
| 186 | + getIDByUK func(context.Context, UK) (INT, error), |
| 187 | + getEntityByID func(context.Context, INT) (*T, error), |
| 188 | +) (*T, error) { |
| 189 | + // 0、若未启用缓存,则直接查询数据库。 |
| 190 | + if Disabled { |
| 191 | + id, err := getIDByUK(ctx, ukVal) |
| 192 | + if err != nil { |
| 193 | + return nil, errors.WithStack(err) |
| 194 | + } |
| 195 | + one, err := getEntityByID(ctx, id) |
| 196 | + if err != nil { |
| 197 | + return nil, errors.WithStack(err) |
| 198 | + } |
| 199 | + return one, nil |
| 200 | + } |
| 201 | + |
| 202 | + // 键:唯一索引值 |
| 203 | + // 值:主键ID |
| 204 | + ukKey := fmt.Sprintf("%s%c%v", ukKeyPrefix, Delimiter, ukVal) |
| 205 | + |
| 206 | + // 1、根据数据库表唯一索引key找到数据库表主键ID |
| 207 | + u64ID, err := cache.GetAsUint64(ctx, ukKey) |
| 208 | + if err == nil { |
| 209 | + // 2、若找到数据库表主键ID,则根据主键ID尝试返回实体对象。 |
| 210 | + return GetEntityByID(ctx, cache, entityKeyPrefix, INT(u64ID), getEntityByID) |
| 211 | + } |
| 212 | + if !cache.IsKeyNotFound(err) { // 发生了除「Redis key不存在」之外的其他未知错误 |
| 213 | + return nil, errors.WithStack(err) |
| 214 | + } |
| 215 | + // 2、若未找到数据库表主键ID,则调用查询函数获取主键ID值。 |
| 216 | + id, err := getIDByUK(ctx, ukVal) |
| 217 | + if err != nil { |
| 218 | + return nil, errors.WithStack(err) |
| 219 | + } |
| 220 | + // 3、保存唯一索引值(键)与主键ID(值)关系 |
| 221 | + if err = cache.Set(ctx, ukKey, fmt.Appendf(nil, "%d", id), 0); err != nil { |
| 222 | + return nil, errors.WithStack(err) |
| 223 | + } |
| 224 | + // 4、根据主键ID尝试返回实体对象 |
| 225 | + return GetEntityByID(ctx, cache, entityKeyPrefix, id, getEntityByID) |
| 226 | +} |
0 commit comments