• mybatis缓存之整合第三方缓存工具ehcache


    1、加入以下依赖包

    2、配置ehcache.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
     <!-- 磁盘保存路径 -->
     <diskStore path="D:44ehcache" />
     
     <defaultCache 
       maxElementsInMemory="10000" 
       maxElementsOnDisk="10000000"
       eternal="false" 
       overflowToDisk="true" 
       timeToIdleSeconds="120"
       timeToLiveSeconds="120" 
       diskExpiryThreadIntervalSeconds="120"
       memoryStoreEvictionPolicy="LRU">
     </defaultCache>
    </ehcache>
     
    <!-- 
    属性说明:
    l diskStore:指定数据在磁盘中的存储位置。
    l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略
     
    以下属性是必须的:
    l maxElementsInMemory - 在内存中缓存的element的最大数目 
    l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
    l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
    l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
     
    以下属性是可选的:
    l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
    l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
     diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
    l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
    l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
    l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
     -->

    3、在mapper.xml中使用

    <mapper namespace="com.gong.mybatis.dao.EmployeeMapper">
        <cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
        ......
    </mapper>

    4、也可以在其它mapper.xml中引用配置好缓存的mapper

    <mapper namespace="com.gong.mybatis.dao.DepartmentMapper">
        <cache-ref namespace="com.gong.mybatis.dao.EmployeeMapper"/>
        ......
    </mapper>

    最后进行测试二级缓存:

    package com.gong.mybatis.test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.Test;
    
    import com.gong.mybatis.bean.Department;
    import com.gong.mybatis.bean.Employee;
    import com.gong.mybatis.dao.EmployeeMapper;
    import com.gong.mybatis.mapper.EmployeeMapperDynamicSql;
    
    public class TestMybatis4 {
        
        public SqlSessionFactory getSqlSessionFactory() throws IOException {
            String resource = "mybatis-config.xml";
            InputStream is = Resources.getResourceAsStream(resource);
            return new SqlSessionFactoryBuilder().build(is);
        }
    
        @Test
        public void test() throws IOException {
            SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
            SqlSession openSession = sqlSessionFactory.openSession();
            SqlSession openSession2 = sqlSessionFactory.openSession();
            
            try {
                EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
                EmployeeMapper mapper2 = openSession2.getMapper(EmployeeMapper.class);
                Employee em = mapper.getEmpById(1);
                System.out.println(em);
                openSession.close();
                Employee em2 = mapper2.getEmpById(1);
                System.out.println(em2);
                openSession.close();
            } finally {
                // TODO: handle finally clause
                
            }
            
        }
        
    }

    输出:

    DEBUG 01-22 11:31:12,291 Configuring ehcache from ehcache.xml found in the classpath: file:/F:/ssmwork/mybatis/bin/ehcache.xml  (ConfigurationFactory.java:132) 
    DEBUG 01-22 11:31:12,307 Configuring ehcache from URL: file:/F:/ssmwork/mybatis/bin/ehcache.xml  (ConfigurationFactory.java:98) 
    DEBUG 01-22 11:31:12,307 Configuring ehcache from InputStream  (ConfigurationFactory.java:150) 
    DEBUG 01-22 11:31:12,417 Ignoring ehcache attribute xmlns:xsi  (BeanHandler.java:271) 
    DEBUG 01-22 11:31:12,417 Ignoring ehcache attribute xsi:noNamespaceSchemaLocation  (BeanHandler.java:271) 
    DEBUG 01-22 11:31:12,417 Disk Store Path: D:44ehcache  (DiskStoreConfiguration.java:141) 
    DEBUG 01-22 11:31:12,448 Creating new CacheManager with default config  (CacheManager.java:1036) 
    DEBUG 01-22 11:31:12,464 propertiesString is null.  (PropertyUtil.java:88) 
    DEBUG 01-22 11:31:12,479 No CacheManagerEventListenerFactory class specified. Skipping...  (ConfigurationHelper.java:185) 
    DEBUG 01-22 11:31:13,072 No BootstrapCacheLoaderFactory class specified. Skipping...  (Cache.java:955) 
    DEBUG 01-22 11:31:13,072 CacheWriter factory not configured. Skipping...  (Cache.java:929) 
    DEBUG 01-22 11:31:13,072 No CacheExceptionHandlerFactory class specified. Skipping...  (ConfigurationHelper.java:96) 
    DEBUG 01-22 11:31:13,119 Initialized net.sf.ehcache.store.MemoryStore for com.gong.mybatis.dao.EmployeeMapper  (MemoryStore.java:152) 
    DEBUG 01-22 11:31:13,181 Using diskstore path D:44ehcache  (DiskStorePathManager.java:169) 
    DEBUG 01-22 11:31:13,181 Holding exclusive lock on D:44ehcache.ehcache-diskstore.lock  (DiskStorePathManager.java:170) 
    DEBUG 01-22 11:31:13,197 Failed to delete file com%002egong%002emybatis%002edao%002e%0045mployee%004dapper.data  (DiskStorageFactory.java:860) 
    DEBUG 01-22 11:31:13,197 Failed to delete file com%002egong%002emybatis%002edao%002e%0045mployee%004dapper.index  (DiskStorageFactory.java:860) 
    DEBUG 01-22 11:31:13,696 Matching data file missing (or empty) for index file. Deleting index file D:44ehcachecom%002egong%002emybatis%002edao%002e%0045mployee%004dapper.index  (DiskStorageFactory.java:168) 
    DEBUG 01-22 11:31:13,712 Failed to delete file com%002egong%002emybatis%002edao%002e%0045mployee%004dapper.index  (DiskStorageFactory.java:860) 
    DEBUG 01-22 11:31:13,759 Initialised cache: com.gong.mybatis.dao.EmployeeMapper  (Cache.java:1165) 
    DEBUG 01-22 11:31:13,759 CacheDecoratorFactory not configured for defaultCache. Skipping for 'com.gong.mybatis.dao.EmployeeMapper'.  (ConfigurationHelper.java:354) 
    DEBUG 01-22 11:31:13,907 Cache Hit Ratio [com.gong.mybatis.dao.EmployeeMapper]: 0.0  (LoggingCache.java:62) 
    DEBUG 01-22 11:31:14,360 ==>  Preparing: select id,last_name lastName,email,gender from tbl_employee where id = ?   (BaseJdbcLogger.java:145) 
    DEBUG 01-22 11:31:14,391 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
    DEBUG 01-22 11:31:14,453 <==      Total: 1  (BaseJdbcLogger.java:145) 
    Employee [id=1, lastName=dema, gender=1, email=dema@qq.com, dept=null]
    DEBUG 01-22 11:31:14,453 put added 0 on heap  (Segment.java:425) 
    DEBUG 01-22 11:31:14,469 Cache Hit Ratio [com.gong.mybatis.dao.EmployeeMapper]: 0.5  (LoggingCache.java:62) 
    Employee [id=1, lastName=dema, gender=1, email=dema@qq.com, dept=null]
    DEBUG 01-22 11:31:14,484 fault removed 0 from heap  (Segment.java:779) 
    DEBUG 01-22 11:31:14,484 fault added 0 on disk  (Segment.java:796) 

    说明配置成功。

  • 相关阅读:
    Delphi Excel 操作大全
    ThreadLocal类
    MyBatis实战总结
    MyBatis入门
    Mybatis逆向工程
    2020年全国高校计算机能力挑战赛初赛java组
    集合论基础
    命题与逻辑
    Redis技术概述
    UML图中6种箭头的含义
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12228262.html
Copyright © 2020-2023  润新知