精尽 MyBatis 源码分析 —— 缓存模块

本文详细分析了MyBatis的缓存模块,包括Cache接口及其多种实现,如PerpetualCache、LoggingCache、BlockingCache等,讨论了它们的特性和应用场景,以及关键类CacheKey的作用。
摘要由CSDN通过智能技术生成

1. 概述

在优化系统性能时,优化数据库性能是非常重要的一个环节,而添加缓存则是优化数据库时最有效的手段之一。正确、合理地使用缓存可以将一部分数据库请求拦截在缓存这一层。

MyBatis 中提供了一级缓存和二级缓存,而这两级缓存都是依赖于基础支持层中的缓 存模块实现的。这里需要读者注意的是,MyBatis 中自带的这两级缓存与 MyBatis 以及整个应用是运行在同一个 JVM 中的,共享同一块堆内存。如果这两级缓存中的数据量较大, 则可能影响系统中其他功能的运行,所以当需要缓存大量数据时,优先考虑使用 Redis、Memcache 等缓存产品

2. Cache

org.apache.ibatis.cache.Cache ,缓存容器接口。注意,它是一个容器,有点类似 HashMap ,可以往其中添加各种缓存。代码如下:

public interface Cache {

    /**
     * @return The identifier of this cache 标识
     */
    String getId();

    /**
     * 添加指定键的值
     *
     * @param key Can be any object but usually it is a {@link CacheKey}
     * @param value The result of a select.
     */
    void putObject(Object key, Object value);

    /**
     * 获得指定键的值
     *
     * @param key The key
     * @return The object stored in the cache.
     */
    Object getObject(Object key);

    /**
     * 移除指定键的值
     *
     * As of 3.3.0 this method is only called during a rollback
     * for any previous value that was missing in the cache.
     * This lets any blocking cache to release the lock that
     * may have previously put on the key.
     * A blocking cache puts a lock when a value is null
     * and releases it when the value is back again.
     * This way other threads will wait for the value to be
     * available instead of hitting the database.
     *
     *
     * @param key The key
     * @return Not used
     */
    Object removeObject(Object key);

    /**
     * 清空缓存
     *
     * Clears this cache instance
     */
    void clear();

    /**
     * 获得容器中缓存的数量
     *
     * Optional. This method is not called by the core.
     *
     * @return The number of elements stored in the cache (not its capacity).
     */
    int getSize();

    /**
     * 获得读取写锁。该方法可以忽略了已经。
     *
     * Optional. As of 3.2.6 this method is no longer called by the core.
     *
     * Any locking needed by the cache must be provided internally by the cache provider.
     *
     * @return A ReadWriteLock
     */
    @Deprecated 
    ReadWriteLock getReadWriteLock();

}

Cache 基于不同的缓存过期策略、特性,有不同的实现类。下面,我们来逐个来看。可以组合多种 Cache ,实现特性的组合。这种方式,就是常见的设计模式

2.1 PerpetualCache

org.apache.ibatis.cache.impl.PerpetualCache ,实现 Cache 接口,永不过期的 Cache 实现类,基于 HashMap 实现类。代码如下:

// PerpetualCache.java

public class PerpetualCache implements Cache {

    /**
     * 标识
     */
    private final String id;
    /**
     * 缓存容器
     */
    private Map<Object, Object> cache = new HashMap<>();

    public PerpetualCache(String id) {
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public int getSize() {
        return cache.size();
    }

    @Override
    public void putObject(Object key, Object value) {
        cache.put(key, value);
    }

    @Override
    public Object getObject(Object key) {
        return cache.get(key);
    }

    @Override
    public Object removeObject(Object key) {
        return cache.remove(key);
    }

    @Override
    public void clear() {
        cache.clear();
    }
    
    // ... 省略 equals 和 hashCode 方法
    
}
2.2 LoggingCache

org.apache.ibatis.cache.decorators.LoggingCache ,实现 Cache 接口,支持打印日志的 Cache 实现类。代码如下:

public class LoggingCache implements Cache {

    /**
     * MyBatis Log 对象
     */
    private final Log log;
    /**
     * 装饰的 Cache 对象
     */
    private final Cache delegate;
    /**
     * 统计请求缓存的次数
     */
    protected int requests = 0;
    /**
     * 统计命中缓存的次数
     */
    protected int hits = 0;

    public LoggingCache(Cache delegate) {
        this.delegate = delegate;
        this.log = LogFactory.getLog(getId());
    }

    @Override
    public String getId() {
        return delegate.getId();
    }

    @Override
    public int getSize() {
        return delegate.getSize();
    }

    @Override
    public void putObject(Object key, Object object) {
        delegate.putObject(key, object);
    }

    @Override
    public Object getObject(Object key) {
        // 请求次数 ++
        requests++;
        // 获得缓存
        final Object value = delegate.getObject(key);
        // 如果命中缓存,则命中次数 ++
        if (value != null) {
            hits++;
        }
        if (log.isDebugEnabled()) {
            log.debug("Cache Hit Ratio [" + getId() + "]: " + getHitRatio());
        }
        return value;
    }

    @Override
    public Object removeObject(Object key) {
        return delegate.removeObject(key);
    }

    @Override
    public void clear() {
        delegate.clear();
    }

    /**
     * @return 命中比率
     */
    private double getHitRatio() {
        return (double) hits / (double) requests;
    }

    // ... 省略 equals 和 hashCode 方法
    
}
2.3 BlockingCache

org.apache.ibatis.cache.decoratorsBlockingCache ,实现 Cache 接口,阻塞的 Cache 实现类。

这里的阻塞比较特殊,当线程去获取缓存值时,如果不存在,则会阻塞后续的其他线程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值