Search code examples
cachingredisredis-cache

Delete and insert Data into Redis Cache every 2 minutes


I have a scenario where I need to sync my MySQL data into redis cache every 2 minutes.

Basically I have 2 tables categories and articles table. Every article belongs to some particular category. Retrieval : I need to fetch articles of particular section and sometimes limiting it.

I saw the 5 data structures available in Redis but getting confused to choose one of them which will be the appropriate for these requirements.

Every 2 minutes the entire data as to be removed and inserted.

So what is the best way I can go on with it.


Solution

  • One suggestion that can serve your scenario is to have:

    • Hash tables to contain your articles and categories.

    • Sorted Set to work as an index for the latest articles per category.

    From the above we will be:

    • Adding objects to hash tables inside Redis for categories and articles. this will make you benefit from a data structure with a constant time complexity in average, as mentioned here.

      HMSET article_with_id_{1234} field1 value1 .. etc

      HMSET category_with_id_{567} field1 value1 .. etc

    • Now you will need the structure to connect them together, Start creating sorted sets as one category -> many articles, below is an example:

      ZADD category_{category_id} {Sorting Score - it could be the article_id in descending order or the timestamp as you mentioned} {article ID}

    Now you should have an index that you can refer to per category. so pulling data will be like :

    ZREVRANGE category_{category_id} 0 10
    

    Pulling the sorted set of the highest scoring 10 articles from that category. now this also will help in pagination.

    From the article IDs you collected, you can pull the detailed info of the articles from their hash with an HGET