Spring @Cacheable encounters null value processing and setting expiration time problem analysis

Problem introduction : The login module will cache the user information in redis, and save it if it is not found. Next time you use user information, first fetch it from the cache, if it is not in the cache, then fetch it from the database to reduce the pressure on the database. This function is based on Sprng @cacheable. When the user logs in with an unregistered account, it will be stored in empty according to the logic. The user immediately registered an account and tried to log in with that account. According to the logic, there are already empty records in the cache and will no longer be retrieved from the database. Check it again, this has caused the account to fail to log in until the time for unified configuration is up, it will be removed from redis.

Problem solving :
First, consider using the unless function of @Cacheable , and not store the empty result in redis, so that all the valid user information in redis:

@Cacheable(value="XXX",key="#info",unless = "#result==null")

The problem just now is solved, but it also brings a new problem: if someone maliciously uses an unregistered account to access, it will cause each request to go directly to the database, which brings pressure to the database, which is data penetration. Problem . Consider that when the user information is empty, still save a copy in redis, and set the expiration time, such as 5s, so that the database penetration problem can be solved. So how to set the timeout? We know that @Cacheable does not support setting the expiration time directly. I considered three ways: The
first one : Spring provides the CacheManager class to set the expiration time for the specified label, and the general configuration is unified in the custom configuration class (@Configuration). We only want to set up a specific account, and only set a 5s expiration for empty data, so this unified setting is not suitable.
The second type : use the aspect, set the point of contact where the call returns the result. Here we should pay attention to the internal call method (that is, the method called with this or omitting this). It is invalid to set the cut point. For detailed analysis, please refer to my reprinted " Shock! Spring Aop does not work, which may be caused by this reason. The
third type : use redisTemplet's opForValue().set() method. It should be noted here that the expire method can only set a timeout for an existing record. Combined with unless, special treatment is given to empty situations to solve the problem.

If you have other ideas, please leave a message.

Guess you like

Origin blog.csdn.net/u013821237/article/details/94734506