synchronized implements double-check lock to avoid Redis cache breakdown

Cache breakdown:

For a certain cache, if its access volume is particularly huge under high concurrency conditions, when the effective time limit of the cache
Upon arrival, there may be a large number of accesses that require the cache to be rebuilt, that is, these access requests find that the cache is
If there is no such data, the query will be carried out immediately in the DBMS , which may cause a problem with the DBMS .
High concurrent queries, which in turn lead to the collapse of the DBMS . This situation is called cache breakdown, and the cache number
It is said to be hot data.
Proceed as follows:
  • First check whether there is data in reids
  • If there is no data in redis, use synchronized for locking
  • Query again whether there is data in reids
  • If there is still no data in the query in step 3, check the database again at this time
  • After querying the data in the database, write the data to redis
public Double findTurnover() {
        // 获取Redis操作对象
        BoundValueOperations<Object, Object> ops = template.boundValueOps("turnover");
        // 从缓存获取turnover
        Object turnover = ops.get();
        //取不到加锁
        if (turnover == null) {
            synchronized (this) {
                turnover = ops.get();
                // 若缓存中没有,则从DB中查询
                if (turnover == null) {
                    Date date = new Date();
                    //根据当前时间获取交易额
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    turnover = dao.selectTurnover(sdf.format(date));
                    // 将从DB中查询的结果写入到缓存,并指定过期时间
                    ops.set(turnover, 10, TimeUnit.SECONDS);
                }
            }
        }
        return (Double) turnover;
    }

Using the double-check lock method can avoid all requests going directly to the database in high concurrency situations.

Guess you like

Origin blog.csdn.net/qq_52183856/article/details/131792774