Generally speaking, as long as you use cache, whether it is Redis or memcache, it may involve the consistency of the database cache and data. Here we take Redis as an example.
#How can we ensure the consistency between Redis and the database?
SO EASY: (Recommended Learning: Redis Video Tutorial )
## When updated, update the database first, and then delete the cache . When reading, read the cache first; if not, read the database, put the data into the cache, and return the response. At first glance, the consistency problem seems to be solved very well. But if you think about it carefully, you will find that there is still a problem: What if you update the database first and fail to delete the cache? Then there is new data in the database and old data in the cache, and the data is inconsistent.Improvement plan:
Delete the cache first, then update the database. Because even if the database update fails later and the cache is empty, it will be pulled from the database again when reading. Although it is all old data, the data is consistent.So the plan becomes:
When updating, delete the cache first, and then update the database. When reading, read the cache first; if not, read the database, put the data into the cache, and return the response.Has the problem been completely solved at this point?
Actually, not really. In a high-concurrency scenario, a situation like this may occur: the data changes, the cache is deleted first, and then the database is modified. Before there was time to modify it, a request came in, I went to read the cache, and found that the cache was empty. I went to read the database, read the old data before modification, and put the old data in the cache. Subsequently, the data change program completed the modification of the database. Then it’s over, data inconsistency occurs at this time...Solution:
The above is the detailed content of How does redis ensure data consistency?. For more information, please follow other related articles on the PHP Chinese website!