go-gorm / caches

Caches Dialector
MIT License
100 stars 10 forks source link

Custom prefix and key in Redis cache. #20

Open rts-gordon opened 5 months ago

rts-gordon commented 5 months ago

Describe the feature

Hi @ktsivkov I queried somethings from DB via gorm-caches, found that the prefix is "gorm-caches" and the keys is a long SQL script, sometimes the long keys have lower performance. Can we customize the prefix and keys? Thank you.

image

mirusky commented 3 months ago

As workaround you could implement somethink like:

func keyer(key string) string {
   hash := md5.Sum([]byte(text))
   return hex.EncodeToString(hash[:])
}

And then in the cacher implementation use it like:

func (c *redisCacher) Get(ctx context.Context, key string, q *caches.Query[any]) (*caches.Query[any], error) {
        key = keyer(key) // hashed key / smaller key
    res, err := c.rdb.Get(ctx, key).Result()
    if err == redis.Nil {
        return nil, nil
    }

    if err != nil {
        return nil, err
    }

    if err := q.Unmarshal([]byte(res)); err != nil {
        return nil, err
    }

    return q, nil
}
rts-gordon commented 3 months ago

@mirusky thanks a lot, I will try this.