Spring RedisCache 偶发死锁
场景说明
spring框架使用redis缓存,使用@cacheable,@cacheput注解
因为缓存击穿导致数据库压力过大,因此我们通过加锁的方式解决,然而spring4.3版本之后增加了cacheable注解增加了sync属性,所以直接用吧。cacheput注解没有sync属性,按理说他是不需要锁的,但是Spring redis框架里面执行到最后又加锁了。最后调试一不小心就死锁了。
spring缓存注解用到的最终核心类结构
按照我们的需求是在@cacheable注解上加锁,spring框架如是这么定义。
spring方法调用流程图
AbstractRedisCacheCallback
static abstract class AbstractRedisCacheCallback<T> implements RedisCallback<T> {
private long WAIT_FOR_LOCK_TIMEOUT = 300;
private final BinaryRedisCacheElement element;
private final RedisCacheMetadata cacheMetadata;
public AbstractRedisCacheCallback(BinaryRedisCacheElement element, RedisCacheMetadata metadata) {
this.element = element;
this.cacheMetadata = metadata;
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.RedisCallback#doInRedis(org.springframework.data.redis.connection.RedisConnection)
*/
@Override
public T doInRedis(RedisConnection connection) throws DataAccessException {
//这里的代码是导致问题的所在的根本原因=====
//waitForLock(connection);//这行注释
return doInRedis(element, connection);
}
//
public abstract T doInRedis(BinaryRedisCacheElement element, RedisConnection connection) throws DataAccessException;
protected void processKeyExpiration(RedisCacheElement element, RedisConnection connection) {
if (!element.isEternal()