(五)MyBatis-缓存机制

本文详细介绍MyBatis中的一级缓存与二级缓存机制,包括缓存的工作原理、配置方式及如何与第三方缓存集成。通过实例解析,帮助读者深入理解缓存的使用场景与优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

缓存介绍

• MyBatis 包含一个非常强大的查询缓存特性,它可以非 常方便地配置和定制。缓存可以极大的提升查询效率。
• MyBatis系统中默认定义了两级缓存。 
• 一级缓存和二级缓存。 
    – 1、默认情况下,只有一级缓存(SqlSession级别的缓存, 也称为本地缓存)开启。
    – 2、二级缓存需要手动开启和配置,他是基于namespace级 别的缓存。
    – 3、为了提高扩展性。MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存,将缓存数据保存到三方缓存里。

一级缓存

      一级缓存:(本地缓存):sqlSession级别的缓存。一级缓存是一直开启的;SqlSession级别的一个Map
      与数据库同一次会话期间查询到的数据会放在本地缓存中。以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库;
       一级缓存失效情况(没有使用到当前一级缓存的情况,效果就是,还需要再向数据库发出查询):
        1、sqlSession不同。
        2、sqlSession相同,查询条件不同.(当前一级缓存中还没有这个数据)
        3、sqlSession相同,两次查询之间执行了增删改操作(这次增删改可能对当前数据有影响),因为增删改标签flushCache="true"
        4、sqlSession相同,手动清除了一级缓存(缓存清空)    sqlsession.clearCache()      

还有一种情况:整合spring之后一级缓存失效:spring对mybatis的sqlsession的使用是由template控制的,sqlsession又被spring当作resource放在当前线程的上下文里(threadlocal),spring通过mybatis调用数据库的过程如下:

           a,我们需要访问数据

           b,spring检查到了这种需求,于是去申请一个mybatis的sqlsession(资源池),并将申请到的sqlsession与当前线程绑定,放入threadlocal里面

           c,template从threadlocal获取到sqlsession,去执行查询

           d,查询结束,清空threadlocal中与当前线程绑定的sqlsession,释放资源

           e,我们又需要访问数据

           f,返回到步骤b

通过以上步骤后发现,同一线程里面两次查询同一数据所使用的sqlsession是不相同的,所以,给人的印象就是结合spring后,mybatis的一级缓存失效了。 

二级缓存

  二级缓存:(全局缓存):基于namespace级别的缓存:一个namespace(mapper.xml文件)对应一个二级缓存:
  工作机制: 查出的数据都会被默认先放在一级缓存中。只有会话提交或者关闭以后,一级缓存中的数据才会转移到二级缓存中
        使用:
            1)、开启全局二级缓存配置:<setting name="cacheEnabled" value="true"/>
            2)、去mapper.xml中配置使用二级缓存: <cache></cache>
            3)、我们的POJO需要实现序列化接口   

<!-- <cache eviction="FIFO" flushInterval="60000" readOnly="false" size="1024"></cache>
	eviction:缓存满时的回收策略:
		• LRU  – 最近最少使用的:移除最长时间不被使用的对象。
		• FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
		• SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
		• WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
		• 默认的是 LRU。
	flushInterval:缓存刷新间隔:缓存多长时间清空一次,默认不清空,设置一个毫秒值
	readOnly:是否只读:
		true:只读;mybatis认为所有从缓存中获取数据的操作都是只读操作,不会修改数据。
		            mybatis为了加快获取速度,直接就会将数据在缓存中的引用交给用户。不安全,速度快
		false:非只读:mybatis觉得获取的数据可能会被修改。
			       mybatis会利用序列化&反序列的技术克隆一份新的数据给你。安全,速度慢
	size:缓存存放多少元素;
	type="":指定自定义缓存的全类名;实现Cache接口即可;
-->

和缓存相关的设置和属性

    1)、全局配置 cacheEnabled=true:false:关闭缓存(二级缓存关闭;一级缓存一直可用的)
    2)、每个select标签都有useCache="true": false:不使用缓存(二级缓存关闭;一级缓存依然使用)
    3)、每个增删改标签的:flushCache="true"(增删改标签默认为true):(一级二级都会清除)】
                         所以同一个sqlsession增删改执行完成后就会清楚缓存;
              每个 查询标签:flushCache="false"(查询标签默认为false):
                         如果flushCache=true;每次查询之后都会清空缓存;缓存是没有被使用的;
    4)、sqlSession.clearCache();只是清楚当前session的一级缓存;
    5)、localCacheScope:本地缓存作用域:(一级缓存SESSION);当前会话的所有数据保存在会话缓存中;
                                       STATEMENT:可以禁用一级缓存;  Mybatis3.3版本以后才有此设置(全局配置中设置)      

第三方缓存整合

        1)、导入第三方缓存包即可;
        2)、导入与第三方缓存整合的适配包;官方有;
        3)、mapper.xml中使用自定义缓存            

        <cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>

        <!-- 引用缓存:namespace:指定和哪个名称空间下的缓存一样 -->
        <cache-ref namespace="com.atguigu.mybatis.dao.EmployeeMapper"/>

例如:整合专业缓存ehcache   

     1.导入三方jar包 

     2.导入mybatis整合的第三方适配包,官方有 

     3.自定义cache实现mybatis的Cache接口(ehcache-mybatis的整合包里已经给写好,ehcache不用自己写,下面贴出来看卡)

     4.类路径下放入ehcache.xml文件

package org.mybatis.caches.ehcache;

public class EhcacheCache extends AbstractEhcacheCache {

  /**
   * Instantiates a new ehcache cache.
   *
   * @param id the id
   */
  public EhcacheCache(String id) {
    super(id);
    if (!CACHE_MANAGER.cacheExists(id)) {
      CACHE_MANAGER.addCache(id);
    }
    this.cache = CACHE_MANAGER.getEhcache(id);
  }

}
package org.mybatis.caches.ehcache;

import java.util.concurrent.locks.ReadWriteLock;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

import org.apache.ibatis.cache.Cache;

/**
 * Cache adapter for Ehcache.
 *
 * @author Simone Tripodi
 */
public abstract class AbstractEhcacheCache implements Cache {

  /**
   * The cache manager reference.
   */
  protected static CacheManager CACHE_MANAGER = CacheManager.create();

  /**
   * The cache id (namespace).
   */
  protected final String id;

  /**
   * The cache instance.
   */
  protected Ehcache cache;

  /**
   * Instantiates a new abstract ehcache cache.
   *
   * @param id the chache id (namespace)
   */
  public AbstractEhcacheCache(final String id) {
    if (id == null) {
      throw new IllegalArgumentException("Cache instances require an ID");
    }
    this.id = id;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void clear() {
    cache.removeAll();
  }

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

  /**
   * {@inheritDoc}
   */
  @Override
  public Object getObject(Object key) {
    Element cachedElement = cache.get(key);
    if (cachedElement == null) {
      return null;
    }
    return cachedElement.getObjectValue();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public int getSize() {
    return cache.getSize();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void putObject(Object key, Object value) {
    cache.put(new Element(key, value));
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Object removeObject(Object key) {
    Object obj = getObject(key);
    cache.remove(key);
    return obj;
  }

  /**
   * {@inheritDoc}
   */
  public void unlock(Object key) {
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (!(obj instanceof Cache)) {
      return false;
    }

    Cache otherCache = (Cache) obj;
    return id.equals(otherCache.getId());
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public int hashCode() {
    return id.hashCode();
  }

  @Override
  public ReadWriteLock getReadWriteLock() {
    return null;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString() {
    return "EHCache {" + id + "}";
  }

  // DYNAMIC PROPERTIES

  /**
   * Sets the time to idle for an element before it expires. Is only used
   * if the element is not eternal.
   *
   * @param timeToIdleSeconds the default amount of time to live for an
   *        element from its last accessed or modified date
   */
  public void setTimeToIdleSeconds(long timeToIdleSeconds) {
    cache.getCacheConfiguration().setTimeToIdleSeconds(timeToIdleSeconds);
  }

  /**
   * Sets the time to idle for an element before it expires. Is only used
   * if the element is not eternal.
   *
   * @param timeToLiveSeconds the default amount of time to live for an
   *        element from its creation date
   */
  public void setTimeToLiveSeconds(long timeToLiveSeconds) {
    cache.getCacheConfiguration().setTimeToLiveSeconds(timeToLiveSeconds);
  }

  /**
   * Sets the maximum objects to be held in memory (0 = no limit).
   *
   * @param maxEntriesLocalHeap The maximum number of elements in
   *        heap, before they are evicted (0 == no limit)
   */
  public void setMaxEntriesLocalHeap(long maxEntriesLocalHeap) {
    cache.getCacheConfiguration().setMaxEntriesLocalHeap(maxEntriesLocalHeap);
  }

  /**
   * Sets the maximum number elements on Disk. 0 means unlimited.
   *
   * @param maxEntriesLocalDisk the maximum number of Elements to
   *        allow on the disk. 0 means unlimited.
   */
  public void setMaxEntriesLocalDisk(long maxEntriesLocalDisk) {
    cache.getCacheConfiguration().setMaxEntriesLocalDisk(maxEntriesLocalDisk);
  }

  /**
   * Sets the eviction policy. An invalid argument will set it to null.
   *
   * @param memoryStoreEvictionPolicy a String representation of
   *        the policy. One of "LRU", "LFU" or "FIFO".
   */
  public void setMemoryStoreEvictionPolicy(String memoryStoreEvictionPolicy) {
    cache.getCacheConfiguration().setMemoryStoreEvictionPolicy(memoryStoreEvictionPolicy);
  }

}

 ehcache.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
 <!-- 磁盘保存路径 -->
 <diskStore path="D:\44\ehcache" />
 
 <defaultCache 
   maxElementsInMemory="10000" 
   maxElementsOnDisk="10000000"
   eternal="false" 
   overflowToDisk="true" 
   timeToIdleSeconds="120"
   timeToLiveSeconds="120" 
   diskExpiryThreadIntervalSeconds="120"
   memoryStoreEvictionPolicy="LRU">
 </defaultCache>
</ehcache>
 
<!-- 
属性说明:
l diskStore:指定数据在磁盘中的存储位置。
l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略
 
以下属性是必须的:
l maxElementsInMemory - 在内存中缓存的element的最大数目 
l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
 
以下属性是可选的:
l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
 diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
 -->

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值