introduce
ehcache is a distributed caching framework.
In order to improve system concurrency, our system generally deploys distributed system (cluster deployment)
Without distributed caching, the cached data is stored separately in each service, which is not convenient for system development. So we need to use distributed caching to centralize the management of cached data.
mybatis cannot implement distributed caching, and needs to be integrated with other distributed caching frameworks. Here I mainly introduce the integration of EhCache. Let's start with an example.
Example
1. Import MyBatis-EhCache package
The project structure is as follows:
2. Add EhCache configuration file (ehcache.xml) under classpath
<ehcache> <diskStore path="F:\cache_test" /> <defaultCache eternal="false" maxElementsInMemory="1000" timeToIdleSeconds="20" timeToLiveSeconds="20" overflowToDisk="true" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="20" memoryStoreEvictionPolicy="LRU" /> </ehcache>
3.MyBatis configuration file (SqlMapConfig.xml) opens secondary cache
<settings> <setting name="cacheEnabled" value="true"/> </settings>
4.Mapper configuration file add cache tag
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
5. Cache result inheritance serialization interface
public class User implements Serializable
test
The test classes are as follows:
package cn.pwc.test; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import cn.pwc.dao.UserMapper; import cn.pwc.pojo.User; public class Test { public static void main(String[] args) { SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(Test.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml")); SqlSession session = factory.openSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.findById(1); System.out.println(user.toString()); session.commit(); session.close(); SqlSession session2 = factory.openSession(); UserMapper mapper2 = session2.getMapper(UserMapper.class); User user2 = mapper2.findById(1); System.out.println(user2.toString()); session2.commit(); session2.close(); } }
The test results are as follows:
DEBUG [cn%002epwc%002edao%002e%0055ser%004dapper.data] net.sf.ehcache.store.disk.Segment - fault removed 0 from heap DEBUG [cn%002epwc%002edao%002e%0055ser%004dapper.data] net.sf.ehcache.store.disk.Segment - fault added 0 on disk
Reproduced in: https://my.oschina.net/u/2400661/blog/596247