package cache import ( "electricity_bill_calc/global" "electricity_bill_calc/tools" "strings" ) const ( STORE_TYPE_KEY = "KEY" STORE_TYPE_SET = "SET" STORE_TYPE_HASH = "HASH" ) func assembleRelationKey(relationName string) string { var keys = make([]string, 0) keys = append(keys, strings.ToUpper(relationName)) return CacheKey(TAG_RELATION, keys...) } func assembleRelationIdentity(storeType, key string, field ...string) string { var identity = make([]string, 0) identity = append(identity, storeType, key) identity = append(identity, field...) return strings.Join(identity, ";") } // 向缓存中保存与指定关联名称相关联的键的名称以及键的类型和子字段的组成。 func CacheRelation(relationName, storeType, key string, field ...string) error { relationKey := assembleRelationKey(relationName) relationIdentity := assembleRelationIdentity(storeType, key, field...) result := global.RedisConn.SAdd(global.Ctx, relationKey, relationIdentity) return result.Err() } // 从缓存中清理指定的关联键 func AbolishRelation(relationName string) error { relationKey := assembleRelationKey(relationName) result := global.RedisConn.SMembers(global.Ctx, relationKey) if result.Err() != nil { return result.Err() } relationItems := result.Val() pipeline := global.RedisConn.Pipeline() for _, item := range relationItems { separated := strings.Split(item, ";") switch separated[0] { case STORE_TYPE_KEY: pipeline.Del(global.Ctx, separated[1]) case STORE_TYPE_HASH: pipeline.HDel(global.Ctx, separated[1], separated[2:]...) case STORE_TYPE_SET: pipeline.SRem(global.Ctx, separated[1], tools.ConvertSliceToInterfaceSlice(separated[2:])...) } } pipeline.Del(global.Ctx, relationKey) _, err := pipeline.Exec(global.Ctx) return err }