怎么用源码解释mybatis二级缓存的默认LRU属性
时间: 2024-03-03 11:46:55 浏览: 85
Mybatis的二级缓存的默认实现是基于LRU(Least Recently Used,最近最少使用)算法的。LRU算法会将最近最少使用的缓存对象淘汰掉,保留最近使用频率较高的缓存对象。
Mybatis的二级缓存是由`org.apache.ibatis.cache.impl.PerpetualCache`类实现的。该类中有一个`HashMap`类型的`cache`属性,用于存放缓存数据。在该类的构造函数中,会将`cache`属性初始化为一个LRU算法实现的`LinkedHashMap`对象:
```java
public PerpetualCache(String id) {
this.id = id;
this.cache = new LinkedHashMap<Object, Object>(DEFAULT_SIZE, .75F, true) {
private static final long serialVersionUID = 1L;
// 当LinkedHashMap中的元素个数超过了DEFAULT_SIZE时,会调用该方法移除最老的元素
@Override
protected boolean removeEldestEntry(Map.Entry<Object, Object> eldest) {
return size() > DEFAULT_SIZE;
}
};
}
```
在上述代码中,`LinkedHashMap`的第三个参数`true`表示启用accessOrder(按访问顺序排序),即当通过`get()`方法获取缓存数据时,会将该数据移动到链表的尾部,以便在淘汰缓存数据时能够优先淘汰最久未使用的数据。
因此,当使用Mybatis默认二级缓存实现时,会自动启用LRU算法,且最大缓存对象数量为1024个。如果需要自定义缓存配置,可以通过在Mybatis配置文件中添加`<cache>`标签来实现。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)