继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【MyBatis】学习纪要七:缓存(一)

冯文议
关注TA
已关注
手记 82
粉丝 1.4万
获赞 707
写在前面的话

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

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

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

总览

S80502-202454.jpg

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

二级缓存属性及设置

<cache
  eviction="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();
}
打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP

热门评论

写的很好?????。

查看全部评论