redis penetrate optimization

General cache design, first of all, if there is no value, and then get data from DB query data from the database cache, write cache after data acquisition. Cache penetration refers to query data that does not exist in the cache layer and DB database can not query the data, and finally return empty data. If the class situation of concurrent access is high, or malicious attacks, may cause DB database downtime.

Solutions are as follows:

  • Null object cache

When DB database can not find the data, setting an empty object, the next query object again, simply return the cache object. Sample code is as follows:

public Goods getById(Long id) {

        if (Objects.isNull(id)) {
            return null;
        }
        String key = GOODS + id;
        String goodsJson = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(goodsJson)) {
            return JSON.parseObject(goodsJson, Goods.class);
        }
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        if (Objects.nonNull(goods)) {
            redisTemplate.opsForValue().set(key, JSON.toJSONString(goods), RedisConst.DEFAULT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
            return goods;
        } else {
            
            // 穿透优化
            redisTemplate.opsForValue().set(key, JSON.toJSONString(new Goods()), RedisConst.DEFAULT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
            return null;
        }
    }

However, there are some problems cache empty object. After the storage space objects require more storage space (if the attack is received, the problem is more serious). You can set a time to failure, it automatically deleted. After a null object caching, and data there will be a data DB database inconsistencies. For example, set the cache expiration time is 2 minutes, during this time, the database and added to the id of the data, there have been inconsistent data cache and the database. In this case, the message system may be utilized to clear the cache, or otherwise.

  • Use bloomfilter filters

For real-time data is relatively small, you can use existing data bloomfilter filter database stored in the cache before the query data, according to bloomfilter filters do a check. If present, during the search operation, conversely, directly returns NULL. This reduces the load DB database to a certain extent, played a protective effect. Since bloomfilter not delete, so this solution is only applicable to real-time data is small, a large amount of data cases.

 

Released eight original articles · won praise 0 · Views 3817

Guess you like

Origin blog.csdn.net/new_com/article/details/104251140