本文以mybatis-3.5.11版本为基础,对mybatis缓存进行较详细的解析。
注意,本文说明的情况,适用于mybatis单独使用的情况,即,不与spring或其他容器框架结合使用的情况。
缓存概念说明
mybatis官方文档中,没有对缓存的明确定义,但引用到了两个缓存概念:
在官方文档中翻找一遍,只有两个概念:本地缓存,二级缓存。并没有一级缓存的概念。本文沿用官方文档说明,使用本地缓存与二级缓存的概念。
本地缓存
mybatis中有SqlSession接口,所有数据库操作,均由该接口完成。使用mybatis时,也需要通过该接口进行数据库操作。
本地缓存,由BaseExecutor的localCache实现,并且是在构造方法中进行初始化,因此,本地缓存,是mybatis所有执行器都具备的缓存功能。
1 protected BaseExecutor(Configuration configuration, Transaction transaction) {
2 ...
3 this.localCache = new PerpetualCache("LocalCache"); // 初始化本地缓存
4 ...
5 }
本地缓存的清空:
统计未必全面,源码中调用路径较多,没有进行全面的检查。
本地缓存key的组成部分中,包含mapper方法签名。例如,org.messi.dao.TestMapper 接口中,有一个 getUser 方法,则签名中包含 org.messi.dao.TestMapper.getUser 串。
因此,本地缓存,仅对同一mapper中的同一方法有效。
二级缓存
相对于本地缓存,二级缓存的实现更有必要进行说明。本地缓存的实现非常直白,操作简单。二级缓存功能强大了一些,实现也绕了一点。
二级缓存的适用范围,不再有同一sqlSession的局限。二级缓存保存在mapperStatement中,但是使用的仍然是与一级缓存相同的key,因此,二级缓存跨sqlSession,但是无法跨mapper。当一个流程中使用一个sqlSession调用多个mapper方法时,这多个mapper的查询语句,都会被缓存起来,并且是在一个缓存之中。下次再调用这个流程时(缓存超时前),多个mapper的方法,都可以走缓存。这是二级缓存支持的重点。
下面用一张图来表示二级缓存的实现原理:

如上图,左边两个mapper,表示XxxMapper.xml映射文件。右边的事务性缓存管理器,是CachingExecutor中的一个属性,因此二级缓存,必须手动开启,才会生效。手动开启后,会使用CachingExecutor对指定的执行器进行装饰,从而获得二级缓存功能。
二级缓存也支持自定义的cache,可以通过自定义cache,实现自己想要的结果。例如使用redis缓存,从而实现分布式部署下的缓存同步。二级缓存的实现原理,到此就描述完毕了。
以下是二级缓存实现的截取相关代码,可以不看。
以下是二级缓存实现的截取相关代码,可以不看。
以下是二级缓存实现的截取相关代码,可以不看。
XxxMapper.xml映射文件的解析代码(XmlConfigBuilder):
1 public Configuration parse() {
2 if (parsed) {
3 throw new BuilderException("Each XMLConfigBuilder can only be used once.");
4 }
5 parsed = true;
6 // 解析配置。这里是对所有配置的解析入口
7 parseConfiguration(parser.evalNode("/configuration"));
8 return configuration;
9 }
解析方法展开:
1 private void parseConfiguration(XNode root) {
2 try {
3 // issue #117 read properties first
4 propertiesElement(root.evalNode("properties"));
5 Properties settings = settingsAsProperties(root.evalNode("settings"));
6 loadCustomVfs(settings);
7 loadCustomLogImpl(settings);
8 typeAliasesElement(root.evalNode("typeAliases"));
9 pluginElement(root.evalNode("plugins"));
10 objectFactoryElement(root.evalNode("objectFactory"));
11 objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
12 reflectorFactoryElement(root.evalNode("reflectorFactory"));
13 settingsElement(settings);
14 // read it after objectFactory and objectWrapperFactory issue #631
15 environmentsElement(root.evalNode("environments"));
16 databaseIdProviderElement(root.evalNode("databaseIdProvider"));
17 typeHandlerElement(root.evalNode("typeHandlers"));
18 // 解析xml映射文件
19 mapperElement(root.evalNode("mappers"));
20 } catch (Exception e) {
21 throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
22 }
23 }
最终解析代码(XMLMapperBuilder):
1 private void configurationElement(XNode context) {
2 try {
3 String namespace = context.getStringAttribute("namespace");
4 if (namespace == null || namespace.isEmpty()) {
5 throw new BuilderException("Mapper's namespace cannot be empty");
6 }
7 builderAssistant.setCurrentNamespace(namespace);
8 cacheRefElement(context.evalNode("cache-ref"));
9 cacheElement(context.evalNode("cache"));
10 parameterMapElement(context.evalNodes("/mapper/parameterMap"));
11 resultMapElements(context.evalNodes("/mapper/resultMap"));
12 sqlElement(context.evalNodes("/mapper/sql"));
13 buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
14 } catch (Exception e) {
15 throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
16 }
17 }
cache标签解析代码(XMLMapperBuilder):
1 private void cacheElement(XNode context) {
2 if (context != null) {
3 String type = context.getStringAttribute("type", "PERPETUAL");
4 // 解析指定的缓存类型。如果没有指定,默认为mybatis的永久缓存类型。
5 Class<? extends Cache> typeClass = typeAliasRegistry.resolveAlias(type);
6 // 解析缓存剔除策略,默认是LRU。
7 String eviction = context.getStringAttribute("eviction", "LRU");
8 Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);
9 Long flushInterval = context.getLongAttribute("flushInterval");
10 Integer size = context.getIntAttribute("size");
11 boolean readWrite = !context.getBooleanAttribute("readOnly", false);
12 boolean blocking = context.getBooleanAttribute("blocking", false);
13 Properties props = context.getChildrenAsProperties();
14 // 创建cache对象
15 builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, blocking, props);
16 }
17 }
cache标签解析缓存对象创建代码(MapperBuilderAssistant):
1 public Cache useNewCache(Class<? extends Cache> typeClass,
2 Class<? extends Cache> evictionClass,
3 Long flushInterval,
4 Integer size,
5 boolean readWrite,
6 boolean blocking,
7 Properties props) {
8 Cache cache = new CacheBuilder(currentNamespace)
9 .implementation(valueOrDefault(typeClass, PerpetualCache.class))
10 .addDecorator(valueOrDefault(evictionClass, LruCache.class))
11 .clearInterval(flushInterval)
12 .size(size)
13 .readWrite(readWrite)
14 .blocking(blocking)
15 .properties(props)
16 .build();
17 configuration.addCache(cache);
18 // 注意这里
19 currentCache = cache;
20 return cache;
21 } public Cache useNewCache(Class<? extends Cache> typeClass,
22 Class<? extends Cache> evictionClass,
23 Long flushInterval,
24 Integer size,
25 boolean readWrite,
26 boolean blocking,
27 Properties props) {
28 Cache cache = new CacheBuilder(currentNamespace)
29 .implementation(valueOrDefault(typeClass, PerpetualCache.class))
30 .addDecorator(valueOrDefault(evictionClass, LruCache.class))
31 .clearInterval(flushInterval)
32 .size(size)
33 .readWrite(readWrite)
34 .blocking(blocking)
35 .properties(props)
36 .build();
37 configuration.addCache(cache);
38 // 注意这里
39 currentCache = cache;
40 return cache;
41 }
缓存对象创建
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po