Mybatis cache is prone to dirty data. It is recommended to use a third-party cache: memcached or redis.

Dirty data in the mybatis level one cache:

Mybatis's first level cache: The default is SqlSession level. As long as the data checked through the session, it will be placed on the session. The next time the data with the same id is queried, it will be directly retrieved from the cache instead of being retrieved from the database. .

Dirty data generated: When different sqlSessions are operating on the database, the first level cache can only ensure that the additions, deletions and changes in the current sqlSession are automatically updated in the first level cache, and dirty data will be generated.

Dirty data in mybatis secondary cache:

Mybatis second-level cache: It is the SessionFactory level and is bound to the namespace. The same namespace is placed in a cache object. When a non-sselect statement is executed in this namaspace, the cache in the entire namespace is cleared.

Dirty data generated: The operations that cause dirty reads usually occur in multi-table association operations. For example, two different mappers involve the addition, deletion, modification, and query operation of the same table, when one of the mappers performs a query operation on this table At this time, another mapper performs an update operation to refresh the cache, and then the first mapper queries again, then the data queried this time is dirty data. The reason for dirty reads is that the caches of their operations are not the same.

Therefore, it is recommended to use a third-party cache: memcached or redis.

How to update the cache in redis to avoid dirty reads?

Reading and writing part:

if(redis存在数据){
    
    
    读取redis数据
}else{
    
    
    数据库读取,同时存redis+设置超时时间

Update part:

if(数据库update){
    
    
    更新redis+设置超时时间

Guess you like

Origin blog.csdn.net/weixin_44371237/article/details/114129326
Recommended