麻城网站建设,外贸网站建设模版,icp查询,企业展厅设计专业的公司区别于redis的分布式缓存#xff0c;ehcache是纯java进程内的单机缓存#xff0c;根据不同的场景可选择使用#xff0c;以下内容主要为springboot整合ehcache以及注意事项添加pom引用dependencygroupIdnet.sf.ehcache/groupIdartifactIdehc…区别于redis的分布式缓存ehcache是纯java进程内的单机缓存根据不同的场景可选择使用以下内容主要为springboot整合ehcache以及注意事项添加pom引用dependencygroupIdnet.sf.ehcache/groupIdartifactIdehcache/artifactIdversion2.10.9.2/version
/dependency启动类添加开启缓存注解EnableCaching添加xml配置注意ehcache需要单独的配置文件?xml version1.0 encodingUTF-8?
ehcache xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:noNamespaceSchemaLocationhttp://ehcache.org/ehcache.xsdupdateCheckfalse!--默认缓存策略 --!-- external是否永久存在设置为true则不会被清除此时与timeout冲突通常设置为false--!-- diskPersistent是否启用磁盘持久化--!-- maxElementsInMemory最大缓存数量--!-- overflowToDisk超过最大缓存数量是否持久化到磁盘--!-- timeToIdleSeconds最大不活动间隔设置过长缓存容易溢出设置过短无效果可用于记录时效性数据例如验证码--!-- timeToLiveSeconds最大存活时间--!-- memoryStoreEvictionPolicy缓存清除策略--defaultCacheeternalfalsediskPersistentfalsemaxElementsInMemory1000overflowToDiskfalsetimeToIdleSeconds60timeToLiveSeconds60memoryStoreEvictionPolicyLRU /cache namecache1eternalfalsediskPersistentfalsemaxElementsInMemory1000overflowToDiskfalsetimeToIdleSeconds2timeToLiveSeconds2memoryStoreEvictionPolicyLRU /
/ehcache
这里我定义了一个缓存名字为cache1修改项目的配置文件application.properties,添加spring缓存类型以及缓存配置文件路径spring.cache.ehcache.configclasspath:ehcache.xml
spring.cache.typeehcache上面的步骤做好之后就可以使用了给你需要加缓存的方法添加注解Configuration
public class TestConfig {Cacheable(value cache1,key #id)public TestController.Person create(String id) {return new TestController.Person();}
}这里的value跟xml配置文件里的一致即可我们调用一下测试看看 GetMapping(/testCache1)public void testCache1(Param(id) String id) throws InterruptedException {Person obj1 testConfig.create(id);Person obj2 testConfig.create(id);Thread.sleep(3000);Person obj3 testConfig.create(id);Person obj4 testConfig.create(id);log.info(test1:obj1.toString());log.info(test2:obj2.toString());log.info(test3:obj3.toString());log.info(test4:obj4.toString());System.out.println(obj1.equals(obj2));}执行一下结果看可以看到obj1跟obj2是同一个对象当程序睡眠了三秒之后再次调用方法就会重新创建对象缓存生效注意事项Cacheable修饰的方法必须是public并且不能是static原理是因为使用了动态代理需要重写方法xml里面的配置要写全要不然项目启动报错就是下图这些xml里面配置的defaultCache没看出有啥用我也没删了试试使用缓存的方法不能在RestController修饰的类中即不能在controller层要不然缓存失效可以在Service、Configuratin、Component等类下面