JavaWeb学习笔记-mybatis-24-查询缓存(二级缓存)

sqlsession1查询用户id为1的用户信息,查询结果放入二级缓存中(需要开启二级缓存)
sqlsession2查询用户id为2的用户信息,去缓存中查找是否有用户id为1的用户信息,有就直接调用
二级缓存范围更大,同一个mapper(namespace)共享一个缓存
执行commit会清空该sql下mapper的二级缓存
开启二级缓存

<!--在SqlMapConfig.xml下配置setting开启二级缓存-->
<setting name="cacheEnabale" value="true"/>

需要在各个namespace下开启二级缓存

<!--开启本mapper的namespace下的二级缓存-->
    <cache/>

调用pojo类实现序列化接口
实现接口Serializable接口,为了将缓存数据取出实现反序列化操作,因为二级缓存存储介质多种多样,不一定在内存中

禁用缓存
在statement中配置属性userCache="false"可以禁用当前sqlstatement的二级缓存
每次查询都需要最新数据的statement可以禁用二级缓存
刷新缓存(清空缓存)
fluhCache="true"
一般情况下执行commit操作时都需要刷新缓存

与ehcache整合
系统为了提高系统并发性能,一般对系统进行分布式缓存(集群部署方式)
不使用分布式缓存,缓存将在各自服务器单独缓存
使用分布式缓存框架,实现对缓存集中管理
框架:redis,ehcache,memached等
mybatis无法实现分布式缓存,需要与其他分布式缓存框架整合
mybatis提供了cache接口,可以实现cache接口,以实现自己的缓存逻辑
mybatis和ehcache整合,mybatis和ehcache整合包中提供了cache接口的实现类
mybatis默认实现的cache类为PerpetualCache
添加依赖

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.ehcache</groupId>
      <artifactId>ehcache</artifactId>
      <version>3.0.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-ehcache -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.0.0</version>
    </dependency>

配置mapper中的cache类型

 <!--开启本mapper的namespace下的二级缓存
    type:指定cache接口实现类型,mybatis默认实现类为PerpetualCache,
    要和ehcahce整合,需要提供ehcache实现cache接口的实现类-->
    <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>

加入ehcache配置文件
ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <diskStore path="F:\develop\ehcache"/>
    <defaultCache
            maxElementsInMemory="10000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"/>
</ehcache>

猜你喜欢

转载自blog.csdn.net/weixin0605/article/details/79322508
今日推荐