2019独角兽企业重金招聘Python工程师标准>>>

写在前面的话

缓存对数据库来说,不是必须,但对于系统来说,缓存是少不了的。我在之前的开发中没有学缓存,也没用到,所以这一次学MyBatis,就来认真学一下,如果你跟我一样,那就来跟我一起学习吧。

我打算这样讲给你听,首先了解一下缓存的大概情况,有缓存的话,查询的顺序是怎样的,再具体看学一下一级缓存,二级缓存,最后我们讨论一些细节。

当然,既然是学习,那就应该深入了解一下,所以在后面的篇幅,我们来学习一下缓存接口的设计,hibernate的缓存,之后,再整合一下Ehcache。这一节我主要学习接口的设计,你们要学习什么,就看各自的需求了。

总览

1、查询时,首先查询二级缓存,如果二级缓存没有,就去查询一级缓存,还是没有,再去查询数据库。

2、通过数据库查询的数据,首先一级缓存在 session中,然后将数据按照Mapper再次进行缓存。

3、缓存这一块,MyBatis提供了Cache接口。显然,我们也可以学习这种设计模式。

一级缓存

一级缓存,简单来说就是在session没关闭,清空之前,如果没经过增、删改操作,如果查询条件没有改变,就不再查询数据库。

1、session没关闭

2、session不清空

3、查询之间没有经过增、删、改操作

4、查询条件不没有改变

二级缓存

二级缓存,应该才是我们用到的核心内容,但是这个我不知道怎么讲,但是我们会在后面花大量篇幅进行代码演示缓存。

我们还是看看MyBatis怎么说缓存的吧:

MyBatis includes a powerful transactional query caching feature which is very configurable and customizable. A lot of changes have been made in the MyBatis 3 cache implementation to make it both more powerful and far easier to configure.

By default, just local session caching is enabled that is used solely to cache data for the duration of a session. To enable a global second level of caching you simply need to add one line to your SQL Mapping file:

<cache/>

Literally that's it. The effect of this one simple statement is as follows:

All results from select statements in the mapped statement file will be cached. All insert, update and delete statements in the mapped statement file will flush the cache. The cache will use a Least Recently Used (LRU) algorithm for eviction. The cache will not flush on any sort of time based schedule (i.e. no Flush Interval). The cache will store 1024 references to lists or objects (whatever the query method returns). The cache will be treated as a read/write cache, meaning objects retrieved are not shared and can be safely modified by the caller, without interfering with other potential modifications by other callers or threads.

NOTE The cache will only apply to statements declared in the mapping file where the cache tag is located. If you are using the Java API in conjunction with the XML mapping files, then statements declared in the companion interface will not be cached by default. You will need to refer to the cache region using the @CacheNamespaceRef annotation.

为了方便阅读,翻译如下:

MyBatis 包含一个非常强大的查询缓存特性,它可以非常方便地配置和定制。MyBatis 3 中的缓存实现的很多改进都已经实现了,使得它更加强大而且易于配置。

默认情况下是没有开启缓存的,除了局部的 session 缓存,可以增强变现而且处理循环 依赖也是必须的。要开启二级缓存,你需要在你的 SQL 映射文件中添加一行:

<cache/> 字面上看就是这样。这个简单语句的效果如下:

映射语句文件中的所有 select 语句将会被缓存。 映射语句文件中的所有 insert,update 和 delete 语句会刷新缓存。 缓存会使用 Least Recently Used(LRU,最近最少使用的)算法来收回。 根据时间表(比如 no Flush Interval,没有刷新间隔), 缓存不会以任何时间顺序 来刷新。 缓存会存储列表集合或对象(无论查询方法返回什么)的 1024 个引用。 缓存会被视为是 read/write(可读/可写)的缓存,意味着对象检索不是共享的,而 且可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。

理解

1、MyBatis支持缓存

2、MyBatis默认需要通过 <cache/> 开启。注意默认一词。

3、增、删、改之后会清空缓存。

4、默认的缓存机制是通过 LRU(Least Recently Used,最近最少使用) 。

5、缓存默认是可读可写的,这是安全的,但需要经过序列化和反序列操作,所以需要时间,相比较不可操作的,来说是很慢的,换句话说,这也是不安全的,将所有权都交给用户了。

二级缓存属性及设置

<cacheeviction="FIFO"flushInterval="60000"size="512"readOnly="true"/>
  • 配置:userCache=false

  • <select ... useCache="false">

  • 增删改,一/二级缓存都清空

<inset flushCache="true">

select标签:flushCache默认是false,如果改为true,每次查询完都清空缓存

  • sqlSession:clearCache()只清除一级缓存

  • localCacheScope 本地缓存作用域,SESSION|STATEMENT(可以禁用一级缓存)

最后,我们来看一下MyBatis官网的详解:

This more advanced configuration creates a FIFO cache that flushes once every 60 seconds, stores up to 512 references to result objects or lists, and objects returned are considered read-only, thus modifying them could cause conflicts between callers in different threads.

The available eviction policies available are:

LRU – Least Recently Used: Removes objects that haven't been used for the longst period of time. FIFO – First In First Out: Removes objects in the order that they entered the cache. SOFT – Soft Reference: Removes objects based on the garbage collector state and the rules of Soft References. WEAK – Weak Reference: More aggressively removes objects based on the garbage collector state and rules of Weak References. The default is LRU.

The flushInterval can be set to any positive integer and should represent a reasonable amount of time specified in milliseconds. The default is not set, thus no flush interval is used and the cache is only flushed by calls to statements.

The size can be set to any positive integer, keep in mind the size of the objects your caching and the available memory resources of your environment. The default is 1024.

The readOnly attribute can be set to true or false. A read-only cache will return the same instance of the cached object to all callers. Thus such objects should not be modified. This offers a significant performance advantage though. A read-write cache will return a copy (via serialization) of the cached object. This is slower, but safer, and thus the default is false.

NOTE Second level cache is transactional. That means that it is updated when a SqlSession finishes with commit or when it finishes with rollback but no inserts/deletes/updates with flushCache=true where executed.

翻译如下

这个更高级的配置创建了一个 FIFO 缓存,并每隔 60 秒刷新,存数结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此在不同线程中的调用者之间修改它们会 导致冲突。

可用的收回策略有:

LRU – 最近最少使用的:移除最长时间不被使用的对象。 FIFO – 先进先出:按对象进入缓存的顺序来移除它们。 SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。 WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。 默认的是 LRU。

flushInterval(刷新间隔)可以被设置为任意的正整数,而且它们代表一个合理的毫秒 形式的时间段。默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新。

size(引用数目)可以被设置为任意正整数,要记住你缓存的对象数目和你运行环境的 可用内存资源数目。默认值是 1024。

readOnly(只读)属性可以被设置为 true 或 false。只读的缓存会给所有调用者返回缓 存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。可读写的缓存 会返回缓存对象的拷贝(通过序列化) 。这会慢一些,但是安全,因此默认是 false。

写在最后

1、测试代码: cache

2、Cache接口

public interface Cache {String getId();int getSize();void putObject(Object key, Object value);Object getObject(Object key);boolean hasKey(Object key);Object removeObject(Object key);void clear();
}

转载于:https://my.oschina.net/fengwenyi/blog/1805847

【MyBatis】学习纪要七:缓存(一)相关推荐

  1. MyBatis学习系列——二级缓存

    [MyBatis学习13]MyBatis中的二级缓存 发表于2016/6/16 7:26:19  4922人阅读 分类: ● 框架技术 --[MyBatis] 1. 二级缓存的原理 前面介绍了,myb ...

  2. Mybatis学习笔记18 - 缓存

    两级缓存: 一级缓存:(本地缓存):sqlSession级别的缓存.一级缓存是一直开启的:SqlSession级别的一个Map 数据库同一次会话期间查询到的数据会放在本地缓存中.以后如果需要获取相同的 ...

  3. MyBatis学习总结(七)——Mybatis缓存

    一.MyBatis缓存介绍 正如大多数持久层框架一样,MyBatis 同样提供了一级缓存和二级缓存的支持 一级缓存: 基于PerpetualCache 的 HashMap本地缓存,其存储作用域为 Se ...

  4. 【Mybatis学习总结七】调用存储过程

    今天这节课本来可以一小时结束的,我却从三点半搞到了九点.我觉得我是世界上最S13的人!!!没有之一!!!!一个小错害我花了一个晚上的时间去寻找,真是够无语的.好了,言归正传,还是先总结下今天学习的内容 ...

  5. mybatis学习8之缓存

    mybatis缓存 MyBatis 内置了一个强大的事务性查询缓存机制,当你查询了一次数据时,他会保存到缓存中,当你第二次查询这个数据时,它不会去数据库查找,而是直接从缓存中去取! 一级缓存 默认情况 ...

  6. SqlMapConfig.xml配置文件---Mybatis学习笔记(七)

    SqlMapConfig.xml文件的配置内容: SqlMapConfig.xml中配置的内容和顺序如下: properties(属性) settings(全局配置参数) typeAliases(类型 ...

  7. mybatis学习(46):二级缓存被刷新的情况

    目录结构 com.geyao.mybatis.mapper BlogMapper类 package com.geyao.mybatis.mapper;import java.util.List; im ...

  8. mybatis学习(44):二级缓存1

    目录结构 com.geyao.mybatis.mapper BlogMapper类 package com.geyao.mybatis.mapper;import java.util.List; im ...

  9. mybatis学习(43):一级缓存被刷新情况

    目录结构 com.geyao.mybatis.mapper BlogMapper类 package com.geyao.mybatis.mapper;import java.util.List; im ...

最新文章

  1. 性能SOTA,国防科技大学单张RGB-D图像预测物体对称性
  2. 一脸懵逼学习Hive的元数据库Mysql方式安装配置
  3. java实现动态上传多个文件并解决文件重名问题
  4. 3、Oracle表空间管理
  5. fastjson 1.1.71.android 版本发布,优化部分场景性能
  6. c语言字符串加减_C语言中指针的介绍
  7. Java文件File操作一:文件的创建和删除
  8. scala List
  9. PyRobot开辟 AI 机器人框架
  10. CAD制图初学入门:使用CAD切换窗口
  11. 从零开始学习音视频编程技术(41) H.264播放器
  12. 大数据学习笔记60:构建Spark机器学习系统
  13. APP性能测试-FPS测试
  14. 雨课堂知识点总结(十六)
  15. 运维是做什么的?史上最全互联网Linux工作规划!十分钟找到linux运维工程师职业方向!...
  16. 云计算与大数据技术应用 第三章
  17. 利用selenium与etree抓取必应图片
  18. 【视频】极值理论EVT与R语言应用:GPD模型火灾损失分布分析
  19. CCS11用户界面介绍2
  20. C#学习之面象对象继承练习(二)

热门文章

  1. 2015-08-07get方式/post方式
  2. Document对象内容集合
  3. javascript的匿名函数
  4. python websocket异步高并发_Python3.5异步和多个websocket服务器
  5. Java中intentfiler_【Android - 组件】之IntentFilter的匹配规则
  6. 2018计算机职称考试题,2018年职称计算机Powerpoint考试试题及答案
  7. android下载后的app自动安装,Android 7.0 下载APK后自动安装
  8. linux命令的使用实验报告,Linux实验报告一-常用命令使用.doc
  9. java 集合存储空字符窜_java中字符串对象和集合的判空
  10. weex css单位,weex 踩坑