N
N
neronru2016-12-26 15:22:01
MySQL
neronru, 2016-12-26 15:22:01

How to synchronize counter between MySQL and Redis?

In general, there is a counter for the number of comments on the article, in order to speed up the work, it was decided to cache part of the data in Redis. The application itself uses socket.io. And it will work on multiple servers.
A hashmap was chosen to store the comment count in Redis. Each time a comment is added / removed in a transaction, an action (INSERT, DELETE) and UPDATE is performed on the counter field, from which the current value of the counter is immediately obtained and put into the radish via HSET. It was done this way, and not through increment / decrement, since the node may fall and the value will not be updated. And so it doesn't matter, not this request, so the next one to correct the quantity. But, here the main problem arose, since the nodes can be on different servers, which creates a delay, there may be an attempt to overwrite the new value with the "old" one.
That is:
Server 1:

  1. incrementing a field value in MySQL and getting the value
  2. -
  3. -
  4. Saving the value in Redis (in fact, this is where the new value is overwritten by the old one)

Server 2:
  1. -
  2. incrementing a field value in MySQL and getting the value
  3. Storing a value in Redis
  4. -

The numbers indicate the order of operations. How can this situation be prevented, the idea with the timestamp only comes to mind, but it also cannot be unique...?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2016-12-26
@Nc_Soft

Why increment, recalculate the number of comments with each new one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question